'use client'
import { useState, useEffect, useCallback } from 'react'
import { useT } from '@/contexts/LangContext'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardActions from '@mui/material/CardActions'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import CircularProgress from '@mui/material/CircularProgress'
import Alert from '@mui/material/Alert'
import MenuItem from '@mui/material/MenuItem'
import TextField from '@mui/material/TextField'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import Snackbar from '@mui/material/Snackbar'
import Grid from '@mui/material/Grid'
import Divider from '@mui/material/Divider'
import Tooltip from '@mui/material/Tooltip'
import IconButton from '@mui/material/IconButton'
import Tab from '@mui/material/Tab'
import Tabs from '@mui/material/Tabs'
import Link from '@mui/material/Link'
import Collapse from '@mui/material/Collapse'
import LinearProgress from '@mui/material/LinearProgress'

const API = '/api'

// ─── Types ─────────────────────────────────────────────────────────────────────

type PracticeArea =
  | 'immigration' | 'corporate' | 'civil_litigation' | 'property'
  | 'family' | 'employment' | 'criminal' | 'other' | 'universal'

interface FormTemplate {
  _id: string
  name: string
  description?: string
  practiceArea: PracticeArea
  storageKey: string
  sourceUrl?: string
  fillMode: 'coordinate' | 'acroform'
  fields: any[]
  isActive: boolean
  isSystem: boolean
  stockId?: string
  needsCalibration: boolean
  createdAt: string
}

// ─── Helpers ───────────────────────────────────────────────────────────────────

const PA_LABELS: Record<string, string> = {
  immigration:      'Immigration',
  corporate:        'Corporate',
  civil_litigation: 'Civil Litigation',
  property:         'Property',
  family:           'Family',
  employment:       'Employment',
  criminal:         'Criminal',
  other:            'Other',
  universal:        'Universal',
}

const PA_COLORS: Record<string, string> = {
  immigration:      '#16B1FF',
  corporate:        '#9C6FDE',
  civil_litigation: '#FF4C51',
  property:         '#56CA00',
  family:           '#FFB400',
  employment:       '#0D9394',
  criminal:         '#FF6B00',
  other:            '#8A8D93',
  universal:        '#2F3349',
}

// ─── Generate Dialog ───────────────────────────────────────────────────────────

function GenerateDialog({
  template,
  onClose,
}: {
  template: FormTemplate
  onClose: (success?: boolean) => void
}) {
  const t = useT()
  const [matterId, setMatterId] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleGenerate = async () => {
    if (!matterId.trim()) return
    setBusy(true)
    setError(null)
    try {
      const res = await fetch(
        `${API}/form-templates/${template._id}/generate?matterId=${encodeURIComponent(matterId.trim())}`,
        { method: 'POST' },
      )
      if (!res.ok) {
        const body = await res.json().catch(() => ({}))
        throw new Error(body.message ?? res.statusText)
      }
      const blob = await res.blob()
      const disposition = res.headers.get('content-disposition') ?? ''
      const match = disposition.match(/filename="([^"]+)"/)
      const filename = match?.[1] ?? `${template.name}.pdf`
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url; a.download = filename; a.click()
      URL.revokeObjectURL(url)
      onClose(true)
    } catch (e: any) {
      setError(e.message ?? t.formTemplates.generateError)
    } finally {
      setBusy(false)
    }
  }

  return (
    <Dialog open onClose={() => onClose()} maxWidth='sm' fullWidth>
      <DialogTitle>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <i className='ri-file-download-line' style={{ color: '#0D9394' }} />
          {t.formTemplates.generateBtn} — {template.name}
        </Box>
      </DialogTitle>
      <DialogContent sx={{ pt: 2 }}>
        {template.needsCalibration && (
          <Alert severity='warning' sx={{ mb: 2 }}>
            {t.formTemplates.calibrationNote}
          </Alert>
        )}
        {error && <Alert severity='error' sx={{ mb: 2 }}>{error}</Alert>}

        <TextField
          label='Matter ID'
          fullWidth size='small'
          value={matterId}
          onChange={e => setMatterId(e.target.value)}
          helperText='Paste or type the Matter _id to fill data from'
          onKeyDown={e => { if (e.key === 'Enter') handleGenerate() }}
        />

        <Box sx={{ mt: 2, p: 1.5, bgcolor: 'action.hover', borderRadius: 1 }}>
          <Typography variant='caption' sx={{ fontWeight: 600, display: 'block', mb: 0.5 }}>
            {t.formTemplates.fields(template.fields.length)} will be auto-filled from client + matter data
          </Typography>
          {template.fields.slice(0, 6).map((f: any) => (
            <Typography key={f.fieldId} variant='caption' color='text.secondary' sx={{ display: 'block', lineHeight: 1.7 }}>
              <i className='ri-arrow-right-s-line' style={{ fontSize: '0.75rem' }} />
              {f.label} ← <code style={{ fontSize: '0.68rem' }}>{f.dataSource}</code>
            </Typography>
          ))}
          {template.fields.length > 6 && (
            <Typography variant='caption' color='text.disabled'>…+{template.fields.length - 6} more fields</Typography>
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={() => onClose()} disabled={busy}>{t.common.cancel}</Button>
        <Button
          variant='contained'
          onClick={handleGenerate}
          disabled={!matterId.trim() || busy}
          startIcon={busy ? <CircularProgress size={14} color='inherit' /> : <i className='ri-download-line' />}
        >
          {busy ? t.formTemplates.generating : t.formTemplates.generateBtn}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

// ─── Template Card ─────────────────────────────────────────────────────────────

function TemplateCard({
  template,
  onGenerate,
}: {
  template: FormTemplate
  onGenerate: (t: FormTemplate) => void
}) {
  const t = useT()
  const color = PA_COLORS[template.practiceArea] ?? '#8A8D93'

  return (
    <Card variant='outlined' sx={{
      height: '100%', display: 'flex', flexDirection: 'column',
      borderColor: color + '44',
      position: 'relative',
    }}>
      {/* Calibration warning strip */}
      {template.needsCalibration && (
        <Box sx={{ bgcolor: '#FFB40022', borderBottom: '1px solid #FFB40044', px: 1.5, py: 0.5, display: 'flex', alignItems: 'center', gap: 0.75 }}>
          <i className='ri-error-warning-line' style={{ fontSize: '0.8rem', color: '#FFB400' }} />
          <Typography variant='caption' sx={{ color: '#FFB400', fontWeight: 600, fontSize: '0.62rem' }}>
            {t.formTemplates.calibrationWarning}
          </Typography>
        </Box>
      )}

      <CardContent sx={{ flex: 1 }}>
        {/* Header */}
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 1 }}>
          <Box sx={{
            width: 34, height: 34, borderRadius: 1.5, flexShrink: 0,
            bgcolor: color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <i className='ri-file-edit-line' style={{ fontSize: '1rem', color }} />
          </Box>
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <Typography variant='subtitle2' sx={{ fontWeight: 600, lineHeight: 1.3, mb: 0.25 }}>
              {template.name}
            </Typography>
            <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
              <Chip
                label={PA_LABELS[template.practiceArea] ?? template.practiceArea}
                size='small'
                sx={{ fontSize: '0.6rem', height: 16, bgcolor: color + '18', color }}
              />
              {template.isSystem && (
                <Chip
                  label={t.formTemplates.stockBadge}
                  size='small'
                  sx={{ fontSize: '0.6rem', height: 16, bgcolor: '#0D939418', color: '#0D9394' }}
                />
              )}
              {template.fillMode === 'acroform' && (
                <Chip label='AcroForm' size='small' sx={{ fontSize: '0.6rem', height: 16 }} />
              )}
            </Box>
          </Box>
          <Chip
            label={template.isActive ? t.formTemplates.templateActive : t.formTemplates.templateInactive}
            size='small'
            color={template.isActive ? 'success' : 'default'}
            sx={{ fontSize: '0.6rem', height: 16, flexShrink: 0 }}
          />
        </Box>

        {template.description && (
          <Typography variant='caption' color='text.secondary' sx={{ display: 'block', mb: 1, lineHeight: 1.45 }}>
            {template.description}
          </Typography>
        )}

        <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}>
          <Typography variant='caption' color='text.disabled'>
            <i className='ri-map-pin-2-line' style={{ fontSize: '0.75rem', marginRight: 2 }} />
            {t.formTemplates.fields(template.fields.length)}
          </Typography>
          {template.sourceUrl && (
            <Link href={template.sourceUrl} target='_blank' rel='noopener' variant='caption' color='primary'
              sx={{ display: 'flex', alignItems: 'center', gap: 0.3 }}>
              <i className='ri-external-link-line' style={{ fontSize: '0.7rem' }} />
              {t.formTemplates.sourceUrl}
            </Link>
          )}
        </Box>
      </CardContent>

      <Divider />

      <CardActions sx={{ px: 2, py: 1 }}>
        <Button
          size='small'
          variant='contained'
          disabled={!template.isActive}
          startIcon={<i className='ri-download-line' style={{ fontSize: '0.8rem' }} />}
          onClick={() => onGenerate(template)}
          sx={{ fontSize: '0.72rem' }}
        >
          {t.formTemplates.generateBtn}
        </Button>
        <Button
          size='small'
          variant='outlined'
          disabled={!template.storageKey}
          startIcon={<i className='ri-eye-line' style={{ fontSize: '0.8rem' }} />}
          onClick={() => window.open(`${API}/form-templates/${template._id}/pdf`, '_blank', 'noopener')}
          sx={{ fontSize: '0.72rem' }}
          title={template.storageKey ? undefined : 'No PDF uploaded yet'}
        >
          View Form
        </Button>
        {template.isSystem && (
          <Typography variant='caption' color='text.disabled' sx={{ ml: 'auto', fontSize: '0.6rem' }}>
            {t.formTemplates.isSystemNote}
          </Typography>
        )}
      </CardActions>
    </Card>
  )
}

// ─── Template Grid ─────────────────────────────────────────────────────────────

function TemplateGrid({
  templates,
  loading,
  areaFilter,
  onGenerate,
  emptyMsg,
  emptyHint,
}: {
  templates: FormTemplate[]
  loading: boolean
  areaFilter: string
  onGenerate: (t: FormTemplate) => void
  emptyMsg: string
  emptyHint?: string
}) {
  const visible = areaFilter === 'all'
    ? templates
    : templates.filter(t => t.practiceArea === areaFilter || t.practiceArea === 'universal')

  if (loading) return (
    <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
      <CircularProgress />
    </Box>
  )

  if (visible.length === 0) return (
    <Box sx={{ textAlign: 'center', py: 10 }}>
      <i className='ri-file-edit-line' style={{ fontSize: '3rem', color: '#ccc' }} />
      <Typography variant='body1' sx={{ mt: 1, fontWeight: 500 }}>{emptyMsg}</Typography>
      {emptyHint && <Typography variant='caption' color='text.secondary'>{emptyHint}</Typography>}
    </Box>
  )

  return (
    <Grid container spacing={2}>
      {visible.map(tpl => (
        <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }} key={tpl._id}>
          <TemplateCard template={tpl} onGenerate={onGenerate} />
        </Grid>
      ))}
    </Grid>
  )
}

// ─── RAG Retrieval Panel (admin-only, kept for manual re-trigger during setup) ─

interface RagResult {
  stockId: string; name: string; status: 'found' | 'not_found' | 'error'
  url?: string; message: string
}
interface RagRun {
  runId: string; startedAt: string; finishedAt?: string
  status: 'running' | 'done' | 'error'
  results: RagResult[]; log: string[]
}

function RagRetrievalPanel({ onRetrieved }: { onRetrieved: () => void }) {
  const t = useT()
  const [run, setRun] = useState<RagRun | null>(null)
  const [busy, setBusy] = useState(false)
  const [logOpen, setLogOpen] = useState(false)

  // Poll while running
  useEffect(() => {
    if (!run || run.status !== 'running') return
    const id = setInterval(async () => {
      try {
        const res = await fetch('/api/rag-agent/status')
        if (!res.ok) return
        const data: RagRun = await res.json()
        setRun(data)
        if (data.status !== 'running') {
          clearInterval(id)
          setBusy(false)
          onRetrieved()  // reload templates
        }
      } catch { /* ignore */ }
    }, 3000)
    return () => clearInterval(id)
  }, [run?.status])

  const startRetrieval = async () => {
    setBusy(true)
    setLogOpen(true)
    const res = await fetch('/api/rag-agent/retrieve-forms', { method: 'POST' })
    const data = await res.json()
    // Start polling
    setRun({ runId: '', startedAt: new Date().toISOString(), status: 'running', results: [], log: [data.message] })
  }

  const found    = run?.results.filter(r => r.status === 'found').length ?? 0
  const notFound = run?.results.filter(r => r.status !== 'found').length ?? 0

  return (
    <Card variant='outlined' sx={{ mb: 2, borderColor: '#0D939444' }}>
      <CardContent sx={{ p: 2, '&:last-child': { pb: 2 } }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
          <Box sx={{ width: 32, height: 32, borderRadius: 1.5, bgcolor: '#0D939418', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <i className='ri-robot-line' style={{ fontSize: '1rem', color: '#0D9394' }} />
          </Box>
          <Box sx={{ flex: 1 }}>
            <Typography variant='subtitle2' sx={{ fontWeight: 700, lineHeight: 1.2 }}>RAG Retrieval Agent</Typography>
            <Typography variant='caption' color='text.secondary'>
              Browses official Thai government portals, finds the current PDF download links, downloads and stores all {12} stock forms
            </Typography>
          </Box>

          {run?.status === 'done' && (
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Chip label={`✓ ${found} retrieved`} size='small' color='success' sx={{ fontSize: '0.65rem', height: 20 }} />
              {notFound > 0 && <Chip label={`✗ ${notFound} not found`} size='small' color='warning' sx={{ fontSize: '0.65rem', height: 20 }} />}
            </Box>
          )}

          <Button
            variant='contained'
            size='small'
            disabled={busy}
            onClick={startRetrieval}
            startIcon={busy
              ? <CircularProgress size={14} color='inherit' />
              : <i className='ri-search-line' style={{ fontSize: '0.85rem' }} />}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' }, fontSize: '0.72rem' }}
          >
            {busy ? 'Agent running…' : 'Retrieve Forms'}
          </Button>

          {run && (
            <IconButton size='small' onClick={() => setLogOpen(o => !o)}>
              <i className={logOpen ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} style={{ fontSize: '1rem' }} />
            </IconButton>
          )}
        </Box>

        {busy && <LinearProgress sx={{ mt: 1.5, borderRadius: 1 }} />}

        <Collapse in={logOpen && !!run}>
          {run && (
            <Box sx={{ mt: 1.5, maxHeight: 300, overflow: 'auto', bgcolor: 'action.hover', borderRadius: 1, p: 1.5 }}>
              {/* Results */}
              {run.results.length > 0 && (
                <Box sx={{ mb: 1.5 }}>
                  {run.results.map(r => (
                    <Box key={r.stockId} sx={{ display: 'flex', alignItems: 'center', gap: 1, py: 0.25 }}>
                      <i className={r.status === 'found' ? 'ri-checkbox-circle-fill' : 'ri-close-circle-line'}
                        style={{ fontSize: '0.85rem', color: r.status === 'found' ? '#56CA00' : '#FF4C51', flexShrink: 0 }} />
                      <Typography variant='caption' sx={{ fontWeight: 600, minWidth: 180 }} noWrap>{r.name}</Typography>
                      <Typography variant='caption' color='text.secondary' noWrap>{r.url ?? r.message}</Typography>
                    </Box>
                  ))}
                  <Divider sx={{ my: 1 }} />
                </Box>
              )}
              {/* Log */}
              {run.log.map((line, i) => (
                <Typography key={i} variant='caption' color='text.secondary'
                  sx={{ display: 'block', fontFamily: 'monospace', fontSize: '0.65rem', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>
                  {line}
                </Typography>
              ))}
            </Box>
          )}
        </Collapse>
      </CardContent>
    </Card>
  )
}

// ─── Law Retrieval Panel ──────────────────────────────────────────────────────

const PRACTICE_AREAS = [
  { value: 'immigration',      label: 'Immigration' },
  { value: 'corporate',        label: 'Corporate' },
  { value: 'property',         label: 'Property' },
  { value: 'employment',       label: 'Employment' },
  { value: 'tax',              label: 'Tax' },
  { value: 'civil_litigation', label: 'Civil Litigation' },
  { value: 'family',           label: 'Family' },
]

interface LawResult {
  title: string; lawType: string; sourceUrl: string
  status: 'stored' | 'linked' | 'error'; message: string
}
interface LawRun {
  runId: string; context: { practiceArea: string; keywords?: string[] }
  startedAt: string; finishedAt?: string
  status: 'running' | 'done' | 'error'
  results: LawResult[]; log: string[]
}

function LawRetrievalPanel() {
  const [run, setRun] = useState<LawRun | null>(null)
  const [busy, setBusy] = useState(false)
  const [logOpen, setLogOpen] = useState(false)
  const [practiceArea, setPracticeArea] = useState('immigration')
  const [keywords, setKeywords] = useState('')

  useEffect(() => {
    if (!run || run.status !== 'running') return
    const id = setInterval(async () => {
      try {
        const res = await fetch('/api/rag-agent/law-status')
        if (!res.ok) return
        const data: LawRun = await res.json()
        setRun(data)
        if (data.status !== 'running') { clearInterval(id); setBusy(false) }
      } catch { /* ignore */ }
    }, 3000)
    return () => clearInterval(id)
  }, [run?.status])

  const startRetrieval = async () => {
    setBusy(true)
    setLogOpen(true)
    const body = {
      practiceArea,
      keywords: keywords.split(',').map(k => k.trim()).filter(Boolean),
    }
    const res = await fetch('/api/rag-agent/fetch-laws', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    })
    const data = await res.json()
    setRun({ runId: '', context: body, startedAt: new Date().toISOString(), status: 'running', results: [], log: [data.message] })
  }

  const stored = run?.results.filter(r => r.status !== 'error').length ?? 0

  return (
    <Card variant='outlined' sx={{ mb: 2, borderColor: '#9C27B044' }}>
      <CardContent sx={{ p: 2, '&:last-child': { pb: 2 } }}>
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1.5, flexWrap: 'wrap' }}>
          <Box sx={{ width: 32, height: 32, borderRadius: 1.5, bgcolor: '#9C27B018', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <i className='ri-scales-3-line' style={{ fontSize: '1rem', color: '#9C27B0' }} />
          </Box>
          <Box sx={{ flex: 1 }}>
            <Typography variant='subtitle2' sx={{ fontWeight: 700, lineHeight: 1.2 }}>RAG Agent — Law Retrieval</Typography>
            <Typography variant='caption' color='text.secondary'>
              Browses official Thai government portals for laws, circulars, and policy updates. Indexes them in the firm's law corpus.
            </Typography>
          </Box>

          {run?.status === 'done' && (
            <Chip label={`${stored} entries indexed`} size='small' color='success' sx={{ fontSize: '0.65rem', height: 20 }} />
          )}
        </Box>

        <Box sx={{ display: 'flex', gap: 1.5, mt: 1.5, flexWrap: 'wrap', alignItems: 'center' }}>
          <TextField
            select size='small' label='Practice Area' value={practiceArea}
            onChange={e => setPracticeArea(e.target.value)}
            sx={{ minWidth: 160, '& .MuiInputBase-input': { fontSize: '0.8rem' } }}
          >
            {PRACTICE_AREAS.map(pa => (
              <MenuItem key={pa.value} value={pa.value} sx={{ fontSize: '0.8rem' }}>{pa.label}</MenuItem>
            ))}
          </TextField>
          <TextField
            size='small' label='Keywords (comma-separated, optional)' value={keywords}
            onChange={e => setKeywords(e.target.value)}
            sx={{ flex: 1, minWidth: 200, '& .MuiInputBase-input': { fontSize: '0.8rem' } }}
            placeholder='e.g. TM.7 extension, visa overstay'
          />
          <Button
            variant='contained'
            size='small'
            disabled={busy}
            onClick={startRetrieval}
            startIcon={busy
              ? <CircularProgress size={14} color='inherit' />
              : <i className='ri-search-eye-line' style={{ fontSize: '0.85rem' }} />}
            sx={{ bgcolor: '#9C27B0', '&:hover': { bgcolor: '#7B1FA2' }, fontSize: '0.72rem', whiteSpace: 'nowrap' }}
          >
            {busy ? 'Agent running…' : 'Fetch Laws'}
          </Button>
          {run && (
            <IconButton size='small' onClick={() => setLogOpen(o => !o)}>
              <i className={logOpen ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} style={{ fontSize: '1rem' }} />
            </IconButton>
          )}
        </Box>

        {busy && <LinearProgress sx={{ mt: 1.5, borderRadius: 1 }} color='secondary' />}

        <Collapse in={logOpen && !!run}>
          {run && (
            <Box sx={{ mt: 1.5, maxHeight: 300, overflow: 'auto', bgcolor: 'action.hover', borderRadius: 1, p: 1.5 }}>
              {run.results.length > 0 && (
                <Box sx={{ mb: 1.5 }}>
                  {run.results.map((r, i) => (
                    <Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, py: 0.25 }}>
                      <i className={r.status !== 'error' ? 'ri-checkbox-circle-fill' : 'ri-close-circle-line'}
                        style={{ fontSize: '0.85rem', color: r.status !== 'error' ? '#56CA00' : '#FF4C51', flexShrink: 0, marginTop: '1px' }} />
                      <Box>
                        <Typography variant='caption' sx={{ fontWeight: 600, display: 'block' }}>{r.title}</Typography>
                        <Typography variant='caption' color='text.secondary' sx={{ fontSize: '0.63rem' }}>{r.lawType} · {r.sourceUrl}</Typography>
                      </Box>
                    </Box>
                  ))}
                  <Divider sx={{ my: 1 }} />
                </Box>
              )}
              {run.log.map((line, i) => (
                <Typography key={i} variant='caption' color='text.secondary'
                  sx={{ display: 'block', fontFamily: 'monospace', fontSize: '0.65rem', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>
                  {line}
                </Typography>
              ))}
            </Box>
          )}
        </Collapse>
      </CardContent>
    </Card>
  )
}

// ─── Calibration Panel ────────────────────────────────────────────────────────

interface CalibResult {
  templateId: string; name: string; status: string
  fieldsFound: number; fieldsMapped: number; fillMode: string; message: string; durationMs: number
}
interface CalibReport {
  startedAt: string; finishedAt?: string
  results: CalibResult[]
  summary: { total: number; acroform: number; coordinate: number; skipped: number; errors: number }
}

function CalibrationPanel() {
  const t = useT()
  const [report, setReport] = useState<CalibReport | null>(null)
  const [running, setRunning] = useState(false)
  const [open, setOpen] = useState(false)

  const fetchStatus = async () => {
    try {
      const res = await fetch(`${API}/form-templates/calibrate/status`)
      if (res.ok) {
        const data = await res.json()
        if (data.results) setReport(data)
      }
    } catch { /* ignore */ }
  }

  const runCalibration = async (force = false) => {
    setRunning(true)
    setOpen(true)
    await fetch(`${API}/form-templates/calibrate/run${force ? '?force=true' : ''}`, { method: 'POST' })
    // Poll until finished
    const poll = setInterval(async () => {
      await fetchStatus()
      const res = await fetch(`${API}/form-templates/calibrate/status`)
      if (res.ok) {
        const data = await res.json()
        if (data.finishedAt) {
          setReport(data)
          setRunning(false)
          clearInterval(poll)
        }
      }
    }, 3000)
    // Stop polling after 10 min
    setTimeout(() => { clearInterval(poll); setRunning(false) }, 600_000)
  }

  useEffect(() => { fetchStatus() }, [])

  const STATUS_COLORS: Record<string, string> = {
    success_acroform:   '#56CA00',
    success_coordinate: '#FFB400',
    skipped:            '#8A8D93',
    error:              '#FF4C51',
  }
  const STATUS_ICONS: Record<string, string> = {
    success_acroform:   'ri-checkbox-circle-fill',
    success_coordinate: 'ri-error-warning-fill',
    skipped:            'ri-skip-forward-line',
    error:              'ri-close-circle-fill',
  }

  return (
    <Box sx={{ mb: 3 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
        <Button
          variant='outlined'
          size='small'
          disabled={running}
          startIcon={running
            ? <CircularProgress size={14} color='inherit' />
            : <i className='ri-robot-line' style={{ fontSize: '0.9rem' }} />}
          onClick={() => runCalibration(false)}
          sx={{ fontSize: '0.72rem' }}
        >
          {running ? t.formTemplates.calibrateRunning : t.formTemplates.calibrateBtn}
        </Button>
        {report && (
          <Button size='small' variant='text' sx={{ fontSize: '0.7rem' }} onClick={() => runCalibration(true)}>
            {t.formTemplates.calForce}
          </Button>
        )}
        {report && (
          <Box sx={{ display: 'flex', gap: 1.5, ml: 1, flexWrap: 'wrap' }}>
            <Chip label={`✓ AcroForm: ${report.summary.acroform}`} size='small' sx={{ bgcolor: '#56CA0022', color: '#56CA00', fontSize: '0.65rem', height: 20 }} />
            <Chip label={`~ Coord: ${report.summary.coordinate}`} size='small' sx={{ bgcolor: '#FFB40022', color: '#FFB400', fontSize: '0.65rem', height: 20 }} />
            {report.summary.errors > 0 && <Chip label={`✗ Errors: ${report.summary.errors}`} size='small' color='error' sx={{ fontSize: '0.65rem', height: 20 }} />}
          </Box>
        )}
        {report && (
          <IconButton size='small' onClick={() => setOpen(o => !o)}>
            <i className={open ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} style={{ fontSize: '1rem' }} />
          </IconButton>
        )}
      </Box>

      {running && <LinearProgress sx={{ mt: 1, borderRadius: 1 }} />}

      <Collapse in={open && !!report}>
        {report && (
          <Card variant='outlined' sx={{ mt: 1.5 }}>
            <CardContent sx={{ p: 2, '&:last-child': { pb: 2 } }}>
              <Typography variant='caption' color='text.secondary' sx={{ display: 'block', mb: 1 }}>
                {t.formTemplates.calibrateStarted}: {new Date(report.startedAt).toLocaleString()}
                {report.finishedAt && ` · ${t.formTemplates.calibrateFinished}: ${new Date(report.finishedAt).toLocaleString()}`}
              </Typography>
              {report.results.map(r => (
                <Box key={r.templateId} sx={{ display: 'flex', alignItems: 'center', gap: 1, py: 0.5 }}>
                  <i className={STATUS_ICONS[r.status] ?? 'ri-question-line'}
                    style={{ fontSize: '0.85rem', color: STATUS_COLORS[r.status] ?? '#888', flexShrink: 0 }} />
                  <Typography variant='caption' sx={{ fontWeight: 600, minWidth: 220 }} noWrap>{r.name}</Typography>
                  <Typography variant='caption' color='text.secondary' sx={{ flex: 1 }}>{r.message}</Typography>
                  {r.fieldsMapped > 0 && (
                    <Chip label={`${r.fieldsMapped} fields`} size='small' sx={{ fontSize: '0.6rem', height: 16 }} />
                  )}
                  <Typography variant='caption' color='text.disabled'>{r.durationMs}ms</Typography>
                </Box>
              ))}
            </CardContent>
          </Card>
        )}
      </Collapse>
    </Box>
  )
}

// ─── Main View ─────────────────────────────────────────────────────────────────

export default function FormTemplatesView() {
  const t = useT()
  const [tab, setTab] = useState(0)
  const [templates, setTemplates] = useState<FormTemplate[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [areaFilter, setAreaFilter] = useState('all')
  const [generateTarget, setGenerateTarget] = useState<FormTemplate | null>(null)
  const [snack, setSnack] = useState<{ open: boolean; msg: string; severity: 'success' | 'error' }>({
    open: false, msg: '', severity: 'success',
  })

  const PRACTICE_AREAS = [
    { value: 'all', label: t.formTemplates.allAreas },
    ...Object.entries(PA_LABELS).map(([v, label]) => ({ value: v, label })),
  ]

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await fetch(`${API}/form-templates`)
      if (!res.ok) throw new Error(res.statusText)
      setTemplates(await res.json())
    } catch (e: any) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { load() }, [load])

  const stockForms  = templates.filter(t => t.isSystem)
  const customForms = templates.filter(t => !t.isSystem)

  const handleGenerateClose = (success?: boolean) => {
    setGenerateTarget(null)
    if (success) setSnack({ open: true, msg: t.formTemplates.generateSuccess, severity: 'success' })
  }

  return (
    <Box>
      {/* Header */}
      <Box sx={{ mb: 3 }}>
        <Typography variant='h5' sx={{ fontWeight: 700, mb: 0.5 }}>{t.formTemplates.title}</Typography>
        <Typography variant='body2' color='text.secondary'>{t.formTemplates.subtitle}</Typography>
      </Box>

      <CalibrationPanel />

      {error && (
        <Alert severity='error' sx={{ mb: 2 }}
          action={<Button size='small' onClick={load}>{t.common.retry}</Button>}>{error}</Alert>
      )}

      {/* Stock library banner */}
      {stockForms.length > 0 && tab === 0 && (
        <Alert
          severity='info'
          icon={<i className='ri-government-line' />}
          sx={{ mb: 2 }}
        >
          {t.formTemplates.stockCount(stockForms.length)}
        </Alert>
      )}

      {/* Tabs */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2, flexWrap: 'wrap' }}>
        <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ borderBottom: 1, borderColor: 'divider', flex: 1 }}>
          <Tab label={`${t.formTemplates.stockLibraryTab} (${stockForms.length})`} />
          <Tab label={`${t.formTemplates.customTab} (${customForms.length})`} />
        </Tabs>

        {/* Filter + reload */}
        <TextField
          select size='small' value={areaFilter}
          onChange={e => setAreaFilter(e.target.value)}
          sx={{ minWidth: 180 }}
        >
          {PRACTICE_AREAS.map(pa => (
            <MenuItem key={pa.value} value={pa.value}>{pa.label}</MenuItem>
          ))}
        </TextField>
        <Tooltip title={t.common.retry}>
          <IconButton size='small' onClick={load} color='primary'>
            <i className='ri-refresh-line' style={{ fontSize: '1rem' }} />
          </IconButton>
        </Tooltip>
      </Box>

      {/* Content */}
      {tab === 0 && (
        <TemplateGrid
          templates={stockForms}
          loading={loading}
          areaFilter={areaFilter}
          onGenerate={setGenerateTarget}
          emptyMsg={t.formTemplates.noTemplates}
          emptyHint='Stock library loads automatically on service start.'
        />
      )}
      {tab === 1 && (
        <TemplateGrid
          templates={customForms}
          loading={loading}
          areaFilter={areaFilter}
          onGenerate={setGenerateTarget}
          emptyMsg={t.formTemplates.noTemplates}
          emptyHint={t.formTemplates.noTemplatesHint}
        />
      )}

      {/* Generate Dialog */}
      {generateTarget && (
        <GenerateDialog template={generateTarget} onClose={handleGenerateClose} />
      )}

      <Snackbar
        open={snack.open}
        autoHideDuration={4000}
        onClose={() => setSnack(s => ({ ...s, open: false }))}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert severity={snack.severity} onClose={() => setSnack(s => ({ ...s, open: false }))}>
          {snack.msg}
        </Alert>
      </Snackbar>
    </Box>
  )
}
