import { useState } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import {
  Alert,
  Badge,
  Button,
  EmptyState,
  LoadingBlock,
  PageHeader,
  Panel,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeaderCell,
  TableRow,
} from '@/ui'
import { useMyDrafts } from '@/api/queries'
import { useWithdrawDraft } from '@/api/mutations'
import type { DraftOperation, DraftStatus } from '@/api/client'

export const Route = createFileRoute('/my-drafts')({
  component: MyDraftsPage,
})

const operationVariant = (op: DraftOperation): 'info' | 'success' | 'warning' => {
  if (op === 'CREATE') return 'success'
  if (op === 'CLOSE') return 'warning'
  return 'info'
}

const statusVariant = (
  s: DraftStatus,
): 'warning' | 'success' | 'error' | 'neutral' => {
  if (s === 'PENDING') return 'warning'
  if (s === 'APPROVED') return 'success'
  if (s === 'REJECTED') return 'error'
  return 'neutral'
}

/**
 * Approval Workflow v2 Phase 4: maker self-tracking. Maker видит свои
 * submissions всех статусов (PENDING/APPROVED/REJECTED/WITHDRAWN), sorted
 * submitted_at DESC. Polled каждые 30s — maker увидит когда reviewer
 * approve/reject. Withdraw кнопка для PENDING (только свои + maker-only
 * gate в backend).
 */
function MyDraftsPage() {
  const { t } = useTranslation()
  const drafts = useMyDrafts(0, 50)
  const withdrawMut = useWithdrawDraft()
  const [busyId, setBusyId] = useState<string | undefined>(undefined)

  const handleWithdraw = (id: string) => {
    if (!confirm(t('myDrafts.confirmWithdraw'))) return
    setBusyId(id)
    withdrawMut.mutate(id, {
      onSettled: () => setBusyId(undefined),
    })
  }

  return (
    <div className="space-y-4">
      <PageHeader
        title={t('myDrafts.title')}
        description={t('myDrafts.description')}
      />

      {drafts.isLoading && <LoadingBlock size="md" label={t('loading')} />}

      {drafts.error && (
        <Alert variant="error" title={t('error.failed')}>
          {String(drafts.error)}
        </Alert>
      )}

      {drafts.data && drafts.data.totalElements === 0 && (
        <EmptyState title={t('myDrafts.empty')} />
      )}

      {drafts.data && drafts.data.totalElements > 0 && (
        <Panel>
          <div className="flex items-center justify-between mb-3">
            <p className="text-cell text-mute">
              {t('myDrafts.total', { count: drafts.data.totalElements })}
            </p>
          </div>
          <Table>
            <TableHead>
              <TableRow>
                <TableHeaderCell>{t('myDrafts.col.bk')}</TableHeaderCell>
                <TableHeaderCell>{t('myDrafts.col.op')}</TableHeaderCell>
                <TableHeaderCell>{t('myDrafts.col.status')}</TableHeaderCell>
                <TableHeaderCell>{t('myDrafts.col.submitted')}</TableHeaderCell>
                <TableHeaderCell>{t('myDrafts.col.reviewed')}</TableHeaderCell>
                <TableHeaderCell>{t('myDrafts.col.reviewer')}</TableHeaderCell>
                <TableHeaderCell>{t('myDrafts.col.comment')}</TableHeaderCell>
                <TableHeaderCell>{t('myDrafts.col.actions')}</TableHeaderCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {drafts.data.items.map((d) => (
                <TableRow key={d.id}>
                  <TableCell className="text-mono">{d.businessKey}</TableCell>
                  <TableCell>
                    <Badge variant={operationVariant(d.operation)}>{d.operation}</Badge>
                  </TableCell>
                  <TableCell>
                    <Badge variant={statusVariant(d.status)}>{d.status}</Badge>
                  </TableCell>
                  <TableCell className="text-cell text-ink-2">
                    {new Date(d.submittedAt).toLocaleString()}
                  </TableCell>
                  <TableCell className="text-cell text-ink-2">
                    {d.reviewedAt
                      ? new Date(d.reviewedAt).toLocaleString()
                      : '—'}
                  </TableCell>
                  <TableCell className="text-mono">
                    {d.reviewerId ?? '—'}
                  </TableCell>
                  <TableCell className="text-cell text-ink max-w-md">
                    {d.reviewComment ?? d.makerComment ?? '—'}
                  </TableCell>
                  <TableCell>
                    {d.status === 'PENDING' ? (
                      <Button
                        variant="secondary"
                        size="sm"
                        disabled={busyId === d.id}
                        onClick={() => handleWithdraw(d.id)}
                      >
                        {t('myDrafts.action.withdraw')}
                      </Button>
                    ) : (
                      <span className="text-cell text-mute/70">—</span>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Panel>
      )}
    </div>
  )
}
