import { useMemo, useRef, useState, type ChangeEvent } from 'react'
import { FileUp, Phone, Users, Wand2 } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { normalizeGhanaPhone, parseRecipients } from '@/lib/sms'
import { cn } from '@/lib/utils'

// The recipients step shared by the SMS and voice composers: one number or a
// pasted/imported list, cleaned and de-duplicated as the customer types.

type Mode = 'single' | 'bulk'

export function useRecipients() {
  const [mode, setMode] = useState<Mode>('bulk')
  const [single, setSingle] = useState('')
  const [recipients, setRecipients] = useState('')
  const parsed = useMemo(() => {
    if (mode === 'single') {
      const phone = normalizeGhanaPhone(single)
      return { valid: phone ? [phone] : [], invalid: single.trim() && !phone ? [single.trim()] : [] }
    }
    return parseRecipients(recipients)
  }, [mode, single, recipients])
  function reset() {
    setSingle('')
    setRecipients('')
  }
  return { mode, setMode, single, setSingle, recipients, setRecipients, parsed, reset }
}

export type RecipientsState = ReturnType<typeof useRecipients>

export function RecipientsField({ state, step, max }: { state: RecipientsState; step: number; max: number }) {
  const { mode, setMode, single, setSingle, recipients, setRecipients, parsed } = state
  const fileInput = useRef<HTMLInputElement>(null)
  const tooMany = parsed.valid.length > max

  async function importFile(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0]
    event.target.value = ''
    if (!file) return
    if (file.size > 2 * 1024 * 1024) {
      toast.error('That file is too large. Use a CSV or TXT file under 2 MB.')
      return
    }
    try {
      const text = await file.text()
      // CSV cells can hold names and other columns, so only keep cells that look like phone numbers.
      const found: string[] = []
      let skipped = 0
      for (const cell of text.split(/[\r\n,;\t"]+/)) {
        const value = cell.trim()
        if (!/\d{7,}/.test(value.replace(/[\s().-]/g, ''))) continue
        const phone = normalizeGhanaPhone(value)
        if (phone) found.push(phone)
        else skipped += 1
      }
      if (found.length === 0) {
        toast.error('No Ghana phone numbers were found in that file.')
        return
      }
      const before = parseRecipients(recipients).valid.length
      const merged = parseRecipients(`${recipients}\n${found.join('\n')}`).valid
      setRecipients(merged.join('\n'))
      toast.success(
        `Added ${(merged.length - before).toLocaleString()} number${merged.length - before === 1 ? '' : 's'} from ${file.name}` +
          (skipped > 0 ? ` · ${skipped} skipped` : ''),
      )
    } catch {
      toast.error('That file could not be read.')
    }
  }

  function cleanList() {
    setRecipients(parsed.valid.join('\n'))
    toast.success('List cleaned: invalid entries and duplicates removed.')
  }

  const rawTokens = mode === 'bulk' ? recipients.split(/[\s,;]+/).filter(Boolean).length : 0
  const duplicates = Math.max(0, rawTokens - parsed.invalid.length - parsed.valid.length)

  return (
    <div className="grid gap-3">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <FieldLabel step={step} htmlFor={mode === 'single' ? 'single-recipient' : 'recipients'}>
          Recipients
        </FieldLabel>
        <div role="radiogroup" aria-label="Send to" className="inline-flex rounded-full bg-muted p-1 text-xs font-semibold">
          {(
            [
              { value: 'single', label: 'One number', icon: Phone },
              { value: 'bulk', label: 'Many numbers', icon: Users },
            ] as const
          ).map((option) => (
            <button
              key={option.value}
              type="button"
              role="radio"
              aria-checked={mode === option.value}
              onClick={() => setMode(option.value)}
              className={cn(
                'inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring',
                mode === option.value ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground',
              )}
            >
              <option.icon className="size-3.5" aria-hidden /> {option.label}
            </button>
          ))}
        </div>
      </div>

      {mode === 'single' ? (
        <div className="grid gap-2">
          <Input
            id="single-recipient"
            type="tel"
            inputMode="tel"
            autoComplete="off"
            value={single}
            onChange={(e) => setSingle(e.target.value)}
            placeholder="0241234567"
            aria-invalid={parsed.invalid.length > 0}
            aria-describedby="single-hint"
            className="h-11 rounded-xl bg-muted/40 font-mono transition-colors focus-visible:bg-card"
            required
          />
          <p id="single-hint" className={cn('text-xs', parsed.invalid.length > 0 ? 'text-destructive' : 'text-muted-foreground')}>
            {parsed.invalid.length > 0
              ? 'Enter a Ghana number like 0241234567 or +233241234567.'
              : parsed.valid.length > 0
                ? `Sending to +${parsed.valid[0]}`
                : 'A Ghana mobile number, with or without +233.'}
          </p>
        </div>
      ) : (
        <div className="grid gap-2">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <span className="text-xs text-muted-foreground tabular-nums" aria-live="polite">
              <span className={cn('font-semibold', tooMany ? 'text-destructive' : 'text-primary')}>
                {parsed.valid.length.toLocaleString()}
              </span>{' '}
              valid
              {duplicates > 0 && <span> · {duplicates.toLocaleString()} duplicate{duplicates === 1 ? '' : 's'}</span>}
              {parsed.invalid.length > 0 && (
                <span className="text-destructive"> · {parsed.invalid.length.toLocaleString()} invalid</span>
              )}
              <span> · max {max.toLocaleString()}</span>
            </span>
            <div className="flex gap-2">
              {(duplicates > 0 || parsed.invalid.length > 0) && (
                <Button type="button" variant="ghost" size="sm" className="h-8 rounded-full" onClick={cleanList}>
                  <Wand2 className="size-3.5" aria-hidden /> Clean list
                </Button>
              )}
              {recipients && (
                <Button type="button" variant="ghost" size="sm" className="h-8 rounded-full" onClick={() => setRecipients('')}>
                  Clear
                </Button>
              )}
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8 rounded-full"
                onClick={() => fileInput.current?.click()}
              >
                <FileUp className="size-3.5" aria-hidden /> Import CSV / TXT
              </Button>
              <input
                ref={fileInput}
                type="file"
                accept=".csv,.txt,text/csv,text/plain"
                className="sr-only"
                tabIndex={-1}
                aria-hidden
                onChange={importFile}
              />
            </div>
          </div>
          <Textarea
            id="recipients"
            value={recipients}
            onChange={(e) => setRecipients(e.target.value)}
            rows={6}
            placeholder={'0241234567\n0201234567, +233271234567'}
            aria-describedby="recipients-hint"
            aria-invalid={tooMany}
            className="max-h-80 rounded-xl bg-muted/40 font-mono text-sm transition-colors focus-visible:bg-card"
            required
          />
          <p id="recipients-hint" className="text-xs text-muted-foreground">
            Paste Ghana numbers separated by new lines, commas or spaces, or import a contacts file exported from
            Excel or Google Sheets. Duplicates are removed automatically.
            {tooMany && (
              <span className="block text-destructive">
                You can send to at most {max.toLocaleString()} numbers at once. Split your list into
                smaller sends.
              </span>
            )}
            {parsed.invalid.length > 0 && (
              <span className="block text-destructive">
                Skipped: {parsed.invalid.slice(0, 5).join(', ')}
                {parsed.invalid.length > 5 && ` and ${parsed.invalid.length - 5} more`}
              </span>
            )}
          </p>
        </div>
      )}
    </div>
  )
}

export function FieldLabel({ step, htmlFor, children }: { step: number; htmlFor: string; children: React.ReactNode }) {
  return (
    <Label htmlFor={htmlFor} className="gap-2.5 text-sm font-semibold">
      <span
        className="grid size-6 place-items-center rounded-lg bg-gradient-to-br from-primary to-[oklch(0.45_0.11_165)] font-display text-xs font-bold text-primary-foreground"
        aria-hidden
      >
        {step}
      </span>
      {children}
    </Label>
  )
}
