import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { Download, FileSpreadsheet } from 'lucide-react'
import { toast } from 'sonner'
import { PageHeader } from '@/components/PageHeader'
import { Button } from '@/components/ui/Button'
import { Label } from '@/components/ui/Label'
import { Select } from '@/components/ui/Select'
import { Input } from '@/components/ui/Input'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import { ContractPhase, ContractPhaseLabel } from '@/types/contracts'

export function ReportsPage() {
  const [phase, setPhase] = useState('')
  const [fromDate, setFromDate] = useState('')
  const [toDate, setToDate] = useState('')

  const exportMut = useMutation({
    mutationFn: async () => {
      const params: Record<string, string> = {}
      if (phase) params.phase = phase
      if (fromDate) params.fromDate = fromDate
      if (toDate) params.toDate = toDate
      const res = await api.get('/reports/contracts/export', { params, responseType: 'blob' })
      const filename = res.headers['content-disposition']?.match(/filename="?([^";]+)"?/)?.[1] ?? 'contracts.xlsx'
      return { blob: res.data as Blob, filename }
    },
    onSuccess: ({ blob, filename }) => {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      a.click()
      URL.revokeObjectURL(url)
      toast.success('Đã tải file')
    },
    onError: err => toast.error(getErrorMessage(err)),
  })

  return (
    <div className="p-6">
      <PageHeader
        title="Báo cáo"
        description="Xuất danh sách HĐ ra Excel theo bộ lọc."
      />

      <div className="max-w-2xl rounded-lg border border-slate-200 bg-white p-6">
        <h2 className="mb-4 flex items-center gap-2 text-sm font-semibold text-slate-700">
          <FileSpreadsheet className="h-4 w-4" />
          Xuất danh sách HĐ (.xlsx)
        </h2>
        <div className="grid grid-cols-2 gap-4">
          <div className="col-span-2 space-y-1.5">
            <Label>Phase</Label>
            <Select value={phase} onChange={e => setPhase(e.target.value)}>
              <option value="">Tất cả phase</option>
              {Object.values(ContractPhase).map(p => (
                <option key={p} value={p}>{ContractPhaseLabel[p]}</option>
              ))}
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label>Từ ngày</Label>
            <Input type="date" value={fromDate} onChange={e => setFromDate(e.target.value)} />
          </div>
          <div className="space-y-1.5">
            <Label>Đến ngày</Label>
            <Input type="date" value={toDate} onChange={e => setToDate(e.target.value)} />
          </div>
        </div>

        <div className="mt-6 flex gap-2">
          <Button onClick={() => exportMut.mutate()} disabled={exportMut.isPending}>
            <Download className="h-4 w-4" />
            {exportMut.isPending ? 'Đang xuất…' : 'Tải Excel'}
          </Button>
        </div>
      </div>

      <div className="mt-6 max-w-2xl rounded-lg border border-dashed border-slate-300 bg-slate-50 p-5 text-sm text-slate-500">
        <strong className="text-slate-700">Báo cáo khác (Phase 4 iteration 2):</strong>
        <ul className="mt-2 list-disc space-y-1 pl-5">
          <li>HĐ quá hạn SLA theo phase / role</li>
          <li>Biểu đồ giá trị HĐ theo tháng / dự án</li>
          <li>Export Approvals history</li>
          <li>Export từng HĐ ra PDF</li>
        </ul>
      </div>
    </div>
  )
}
