import { Button, Checkbox, SectionCard, Select, TextField } from '@overdeck/deck-ui'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { saveRoutingConfig, type RoutingProvider, type RoutingRules } from '../../lib/collector-client'
import { collectorQueryKeys, useRoutingConfig } from '../../lib/collector-queries'
import { CollectorQueryBoundary } from '../shared/CollectorQueryBoundary'

const PROVIDER_LABEL: Record<RoutingProvider, string> = { codex: 'Codex', claude: 'Claude' }

export function RoutingRulesEditor({ provider }: { provider: RoutingProvider }) {
  const query = useRoutingConfig(provider)
  return (
    <CollectorQueryBoundary query={query}>
      {(config) => <RoutingRulesForm provider={provider} accounts={config.accounts} rules={config.rules} />}
    </CollectorQueryBoundary>
  )
}

function RoutingRulesForm({ provider, accounts, rules }: {
  provider: RoutingProvider
  accounts: string[]
  rules: RoutingRules
}) {
  const queryClient = useQueryClient()
  const [draft, setDraft] = useState(rules)
  const [message, setMessage] = useState<string | null>(null)
  useEffect(() => setDraft(rules), [rules])
  const accountOptions = accounts.map((slug) => ({ value: slug, label: slug }))
  const mutation = useMutation({
    mutationFn: () => saveRoutingConfig(provider, draft),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: collectorQueryKeys.routingConfig(provider) })
      setMessage(`Saved ${PROVIDER_LABEL[provider]} routing rules`)
    },
    onError: (error) => setMessage(error instanceof Error ? error.message : 'Save failed'),
  })
  const projects = Object.entries(draft.projects)

  return (
    <SectionCard title={`${PROVIDER_LABEL[provider]} account routing`}>
      <div className="flex flex-col gap-4">
        <div className="grid gap-3 md:grid-cols-2">
          <Select label="Default account" value={draft.default} options={accountOptions}
            onValueChange={(value) => setDraft((current) => ({ ...current, default: value }))} />
          <TextField label="Fallback chain" value={draft.fallback_chain.join(', ')} hint="Account slugs, in order, separated by commas"
            onValueChange={(value) => setDraft((current) => ({ ...current, fallback_chain: value.split(',').map((slug) => slug.trim()).filter(Boolean) }))} />
          <Select label="Fallback trigger" value={draft.fallback_trigger} options={[
            { value: 'broken_or_quota_exhausted', label: 'Broken or quota exhausted' },
            { value: 'broken_only', label: 'Broken only' },
          ]} onValueChange={(value) => setDraft((current) => ({ ...current, fallback_trigger: value as RoutingRules['fallback_trigger'] }))} />
          <TextField label="Quota exhausted threshold (%)" type="number" min={1} max={100}
            value={String(draft.quota_exhausted_threshold_pct)}
            onValueChange={(value) => setDraft((current) => ({ ...current, quota_exhausted_threshold_pct: Number(value) }))} />
        </div>
        <Checkbox label="Treat missing health as available" checked={draft.missing_health_is_available}
          onCheckedChange={(checked) => setDraft((current) => ({ ...current, missing_health_is_available: checked }))} />

        <div className="flex flex-col gap-2">
          <div className="text-xs font-semibold text-fg">Per-project overrides</div>
          {projects.length === 0 ? <p className="text-xs text-fg-muted">No project overrides.</p> : null}
          {projects.map(([project, slug], index) => (
            <div className="flex flex-col gap-2 md:flex-row md:items-start" key={`${project}-${index}`}>
              <div className="md:flex-1">
                <TextField label={`Project ${index + 1}`} labelMode="hidden" value={project} placeholder="Project name"
                  onValueChange={(value) => setDraft((current) => {
                    const next = { ...current.projects }; delete next[project]; if (value) next[value] = slug
                    return { ...current, projects: next }
                  })} />
              </div>
              <div className="md:flex-1">
                <Select label={`Account for ${project}`} labelMode="hidden" value={slug} options={accountOptions}
                  onValueChange={(value) => setDraft((current) => ({ ...current, projects: { ...current.projects, [project]: value } }))} />
              </div>
              <Button variant="ghost" tone="danger" size="sm" aria-label={`Remove ${project} override`}
                onClick={() => setDraft((current) => { const next = { ...current.projects }; delete next[project]; return { ...current, projects: next } })}>Remove</Button>
            </div>
          ))}
          <Button variant="outline" tone="neutral" size="sm" className="w-fit"
            onClick={() => setDraft((current) => ({ ...current, projects: { ...current.projects, '': accounts[0] ?? '' } }))}>Add override</Button>
        </div>

        <div className="flex flex-col gap-2">
          <div className="text-xs font-semibold text-fg">Account caps</div>
          {accounts.map((slug) => (
            <div className="grid gap-2 md:grid-cols-3" key={slug}>
              <div className="flex min-h-11 items-center text-sm font-medium text-fg">{slug}</div>
              {(['5h', '7d'] as const).map((window) => <TextField key={window} label={`${window} cap (%)`} type="number" min={1} max={100}
                value={draft.account_caps[slug]?.[window]?.toString() ?? ''} placeholder="No cap"
                onValueChange={(value) => setDraft((current) => {
                  const caps = { ...current.account_caps }; const account = { ...caps[slug] }
                  if (value === '') delete account[window]; else account[window] = Number(value)
                  if (Object.keys(account).length) caps[slug] = account; else delete caps[slug]
                  return { ...current, account_caps: caps }
                })} />)}
            </div>
          ))}
        </div>

        <div className="flex items-center gap-3">
          <Button size="sm" disabled={mutation.isPending} onClick={() => { setMessage(null); mutation.mutate() }}>Save routing rules</Button>
          {message ? <p role="status" className="text-xs text-fg-muted">{message}</p> : null}
        </div>
      </div>
    </SectionCard>
  )
}
