import { useState } from 'react'
import { useServerFn } from '@tanstack/react-start'
import { Loader2, ScanSearch } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { analyzeIssue } from '@/lib/issue-advisor.functions'

const categories = [['receivables', 'Receivables'], ['payment', 'Payment'], ['reconciliation', 'Reconciliation'], ['customer', 'Customer behaviour']] as const
const examples = [
  'Coal City Supplies paid $460 with a bank memo that doesn’t reference any invoice. We have two open invoices for them of $460 and $230.',
  'Three customers who normally pay within 20 days are now past 45 days on invoices issued in August.',
]

function Rendered({ text }: { text: string }) {
  return <div className="space-y-2 text-sm leading-7">{text.split('\n').map((line, i) => {
    const l = line.trim()
    if (!l) return null
    if (l.startsWith('## ')) return <h3 key={i} className="pt-4 font-serif text-lg text-foreground first:pt-0">{l.slice(3)}</h3>
    const clean = l.replace(/\*\*(.+?)\*\*/g, '$1')
    if (/^[-*] /.test(clean)) return <p key={i} className="pl-4 text-muted-foreground before:-ml-4 before:mr-2 before:content-['—']">{clean.slice(2)}</p>
    return <p key={i} className="text-muted-foreground">{clean}</p>
  })}</div>
}

export function IssueAdvisor() {
  const run = useServerFn(analyzeIssue)
  const [category, setCategory] = useState<(typeof categories)[number][0]>('receivables')
  const [description, setDescription] = useState('')
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState('')
  const [error, setError] = useState('')
  async function submit(e: React.FormEvent) {
    e.preventDefault()
    if (description.trim().length < 15) { setError('Describe the issue in a little more detail (at least 15 characters).'); return }
    setLoading(true); setError(''); setResult('')
    try {
      const r = await run({ data: { category, description } })
      if (r.ok) setResult(r.text); else setError(r.error)
    } catch { setError('The advisor could not complete this analysis. Please try again.') }
    finally { setLoading(false) }
  }
  return <section className="mt-6 grid gap-6 rounded-lg border border-border bg-panel p-6 xl:grid-cols-[1fr_1.2fr]">
    <form onSubmit={submit}>
       <div className="flex items-center gap-2"><ScanSearch className="size-5 text-primary" /><h2 className="font-serif text-xl">Issue Advisor <span className="font-sans text-xs text-muted-foreground">In Pilot</span></h2></div>
      <p className="mt-2 text-sm leading-6 text-muted-foreground">Describe a receivables or payment problem. The advisor explains what is likely happening and recommends next actions.</p>
      <div className="mt-5 flex flex-wrap gap-2">{categories.map(([v, l]) => <Button key={v} type="button" size="sm" variant={category === v ? 'default' : 'outline'} onClick={() => setCategory(v)}>{l}</Button>)}</div>
      <Label htmlFor="issue" className="mt-5 block">Describe the issue</Label>
      <Textarea id="issue" value={description} onChange={e => setDescription(e.target.value)} maxLength={3000} rows={6} className="mt-2" placeholder="e.g. A customer transfer arrived without an invoice reference…" />
      <div className="mt-2 flex flex-wrap gap-2">{examples.map((x, i) => <button key={i} type="button" onClick={() => setDescription(x)} className="text-left text-xs text-muted-foreground underline-offset-4 hover:underline">Use example {i + 1}</button>)}</div>
      <Button className="mt-5" disabled={loading}>{loading ? <><Loader2 className="size-4 animate-spin" />Analysing…</> : 'Analyse issue'}</Button>
      <p className="mt-4 font-mono text-[10px] uppercase tracking-[.12em] text-muted-foreground">AI-generated guidance · Review before acting</p>
    </form>
    <div className="min-h-64 border border-border bg-background p-5" aria-live="polite">
      {loading ? <div className="space-y-3">{[80, 95, 70, 88, 60].map(w => <div key={w} className="h-3 animate-pulse rounded bg-muted" style={{ width: `${w}%` }} />)}</div>
        : error ? <p className="text-sm text-destructive">{error}</p>
        : result ? <Rendered text={result} />
        : <p className="text-sm leading-7 text-muted-foreground">Your analysis will appear here, structured into likely cause, recommended actions, what to check, and risk to watch.</p>}
    </div>
  </section>
}
