import { useState, useEffect, useCallback, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Search, Loader2, Receipt, RefreshCw, Eye, FileText, IndianRupee, CalendarClock } from 'lucide-react';
import { toast } from 'sonner';
import {
  listDebitNotes,
  getDebitNoteSapResponse,
  type Form16DebitNoteListItem,
  type Form16SapResponseRecord,
  type ListDebitNotesParams,
  type ListDebitNotesSummary,
} from '@/services/form16Api';
import apiClient from '@/services/authApi';

function formatDate(value: string | null | undefined): string {
  if (!value) return '–';
  try {
    const d = new Date(value);
    return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
  } catch {
    return value;
  }
}

function formatAmount(value: number | null | undefined): string {
  if (value == null) return '–';
  return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(value);
}

function formatIssuedAt(value: string | null | undefined): string {
  if (!value) return '–';
  try {
    const d = new Date(value);
    return Number.isNaN(d.getTime())
      ? value
      : d.toLocaleString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
  } catch {
    return value;
  }
}

function mapSapResponseToPreviewRow(sap: Form16SapResponseRecord): Record<string, string> {
  return {
    TRNS_UNIQ_NO: sap.trnsUniqNo || '',
    TDS_TRNS_ID: sap.tdsTransId || '',
    DOC_NO: sap.sapDocumentNumber || '',
    MSG_TYP: sap.msgTyp || '',
    MESSAGE: sap.message || '',
  };
}

const DEFAULT_SUMMARY: ListDebitNotesSummary = {
  totalDebitNotes: 0,
  totalAmount: 0,
  impactedDealersCount: 0,
};

export function Form16DebitNotes() {
  const [debitNotes, setDebitNotes] = useState<Form16DebitNoteListItem[]>([]);
  const [summary, setSummary] = useState<ListDebitNotesSummary>(DEFAULT_SUMMARY);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [previewRow, setPreviewRow] = useState<Record<string, string> | null>(null);
  const [previewMeta, setPreviewMeta] = useState<{ amountText: string; issuedAtText: string } | null>(null);
  const [pulling, setPulling] = useState(false);

  const fetchNotes = useCallback(async (params?: ListDebitNotesParams) => {
    try {
      setLoading(true);
      const result = await listDebitNotes(params);
      setDebitNotes(result.debitNotes);
      setSummary(result.summary ?? DEFAULT_SUMMARY);
    } catch (error: unknown) {
      console.error('[Form16DebitNotes] Failed to fetch:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to load debit notes');
      setDebitNotes([]);
      setSummary(DEFAULT_SUMMARY);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchNotes();
  }, [fetchNotes]);

  const filteredNotes = useMemo(() => {
    if (!searchQuery.trim()) return debitNotes;
    const q = searchQuery.trim().toLowerCase();
    return debitNotes.filter(
      (n) =>
        (n.debitNoteNumber && n.debitNoteNumber.toLowerCase().includes(q)) ||
        (n.creditNoteNumber && n.creditNoteNumber.toLowerCase().includes(q)) ||
        (n.dealerName && n.dealerName.toLowerCase().includes(q)) ||
        (n.dealerCode && n.dealerCode.toLowerCase().includes(q)) ||
        (n.form16aNumber && n.form16aNumber.toLowerCase().includes(q))
    );
  }, [debitNotes, searchQuery]);

  const openSapPreview = useCallback(async (note: Form16DebitNoteListItem) => {
    setPreviewOpen(true);
    setPreviewLoading(true);
    setPreviewRow(null);
    setPreviewMeta({ amountText: formatAmount(note.amount), issuedAtText: formatIssuedAt(note.issueDate) });
    try {
      const payload = await getDebitNoteSapResponse(Number(note.id));
      setPreviewRow(mapSapResponseToPreviewRow(payload.sapResponse));
    } catch (e: any) {
      const msg =
        e?.response?.status === 409
          ? 'The debit note is being generated, wait.'
          : (e instanceof Error ? e.message : 'Failed to load SAP response');
      toast.error(String(msg));
      setPreviewOpen(false);
    } finally {
      setPreviewLoading(false);
    }
  }, []);

  const pullNow = useCallback(async () => {
    setPulling(true);
    toast.loading('Pulling SAP responses...', { id: 'pull-debit' });
    try {
      const res = await apiClient.post<{ data?: { processed?: number; debitProcessed?: number }; message?: string }>('/form16/sap/pull');
      await fetchNotes();
      const data = res.data?.data;
      const debitCount = typeof data?.debitProcessed === 'number' ? data.debitProcessed : data?.processed;
      if (typeof debitCount === 'number' && debitCount > 0) {
        toast.success(`Pulled. ${debitCount} debit response(s) processed. List refreshed.`, { id: 'pull-debit' });
      } else {
        toast.success('Pulled. List refreshed. (No new debit responses in folder.)', { id: 'pull-debit' });
      }
    } catch {
      toast.error('Failed to pull SAP responses', { id: 'pull-debit' });
    } finally {
      setPulling(false);
    }
  }, [fetchNotes]);

  return (
    <div className="space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full">
      <Dialog
        open={previewOpen}
        onOpenChange={(open) => {
          setPreviewOpen(open);
          if (!open) {
            setPreviewRow(null);
            setPreviewMeta(null);
          }
        }}
      >
        <DialogContent className="sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>SAP Response</DialogTitle>
            <DialogDescription>
              {previewLoading ? 'Loading SAP response CSV…' : 'Review SAP response details.'}
            </DialogDescription>
          </DialogHeader>

          {previewLoading ? (
            <div className="py-8 flex items-center justify-center gap-2 text-gray-600">
              <Loader2 className="w-5 h-5 animate-spin" />
              Loading SAP response…
            </div>
          ) : previewRow ? (
            <div className="space-y-4">
              {/* Block 1 (green): TRNS_UNIQ_NO + TDS_TRNS_ID */}
              <div className="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4">
                <div className="flex items-center gap-2">
                  <FileText className="w-4 h-4 text-emerald-700" />
                  <p className="text-xs font-semibold text-emerald-800 tracking-wide uppercase">SAP Response Identifiers</p>
                </div>
                <div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div className="rounded-lg border border-emerald-200 bg-white/70 p-3">
                    <p className="text-xs text-emerald-700 uppercase tracking-wide">TRNS_UNIQ_NO</p>
                    <p className="text-sm font-semibold text-emerald-900 break-all mt-1">{previewRow['TRNS_UNIQ_NO'] || '–'}</p>
                  </div>
                  <div className="rounded-lg border border-emerald-200 bg-white/70 p-3">
                    <p className="text-xs text-emerald-700 uppercase tracking-wide">TDS_TRNS_ID</p>
                    <p className="text-sm font-semibold text-emerald-900 break-all mt-1">{previewRow['TDS_TRNS_ID'] || '–'}</p>
                  </div>
                </div>
              </div>

              {/* Block 2 (yellow): AMOUNT, DOC_NO, MSG_TYP, MESSAGE, ISSUED DATE */}
              <div className="rounded-xl border border-amber-200 bg-amber-50/70 p-4">
                <div className="flex items-center gap-2 mb-3">
                  <IndianRupee className="w-4 h-4 text-amber-700" />
                  <p className="text-xs font-semibold text-amber-800 tracking-wide uppercase">Debit Note Details</p>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div className="rounded-lg border border-amber-200 bg-white/70 p-3">
                    <p className="text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2">
                      <IndianRupee className="w-4 h-4" /> Amount
                    </p>
                    <p className="text-base font-semibold text-amber-900 mt-1">{previewMeta?.amountText ?? '–'}</p>
                  </div>
                  <div className="rounded-lg border border-amber-200 bg-white/70 p-3">
                    <p className="text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2">
                      <CalendarClock className="w-4 h-4" /> Issued Date
                    </p>
                    <p className="text-base font-semibold text-amber-900 mt-1">{previewMeta?.issuedAtText ?? '–'}</p>
                  </div>
                  <div className="rounded-lg border border-amber-200 bg-white/70 p-3">
                    <p className="text-xs text-amber-700 uppercase tracking-wide">DOC_NO</p>
                    <p className="text-sm font-semibold text-amber-900 break-all mt-1">{previewRow['DOC_NO'] || '–'}</p>
                  </div>
                  <div className="rounded-lg border border-amber-200 bg-white/70 p-3">
                    <p className="text-xs text-amber-700 uppercase tracking-wide">MSG_TYP</p>
                    <p className="text-sm font-semibold text-amber-900 break-all mt-1">{previewRow['MSG_TYP'] || '–'}</p>
                  </div>
                </div>

                <div className="rounded-lg border border-amber-200 bg-white/70 p-3 mt-3">
                  <p className="text-xs text-amber-700 uppercase tracking-wide">MESSAGE</p>
                  <p className="text-sm font-medium text-amber-900 break-words mt-1">{previewRow['MESSAGE'] || '–'}</p>
                </div>
              </div>
            </div>
          ) : (
            <div className="py-8 text-sm text-gray-600">No preview available.</div>
          )}

          <DialogFooter className="gap-2 sm:gap-0">
            <Button variant="outline" onClick={() => setPreviewOpen(false)}>
              Close
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-2">Debit Notes</h1>
          <p className="text-sm text-gray-600">View all issued debit notes</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>Total Debit Notes Issued</CardDescription>
              <CardTitle className="text-3xl">{loading ? '...' : summary.totalDebitNotes}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>Total Debit Amount</CardDescription>
              <CardTitle className="text-3xl text-red-600">{loading ? '...' : formatAmount(summary.totalAmount)}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>Impacted Dealers</CardDescription>
              <CardTitle className="text-3xl">{loading ? '...' : summary.impactedDealersCount}</CardTitle>
            </CardHeader>
          </Card>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>All Debit Notes</CardTitle>
            <CardDescription>Search by debit note number, credit note number, dealer, or Form 16A number</CardDescription>
            <div className="relative max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                type="search"
                placeholder="Search debit notes..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
          </CardHeader>
          <CardContent>
            <div className="rounded-lg border overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Debit Note No.</TableHead>
                    <TableHead>Credit Note No.</TableHead>
                    <TableHead>Dealer</TableHead>
                    <TableHead>Form 16A No.</TableHead>
                    <TableHead>Amount</TableHead>
                    <TableHead>Issue Date</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-12">
                        <Loader2 className="w-6 h-6 animate-spin mx-auto mb-2 text-teal-600" />
                        <p className="text-gray-500">Loading debit notes...</p>
                      </TableCell>
                    </TableRow>
                  ) : filteredNotes.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-12 text-gray-500">
                        <Receipt className="w-12 h-12 mx-auto mb-3 text-gray-400" />
                        <p>No debit notes found</p>
                        <p className="text-sm mt-1">{searchQuery.trim() ? 'Try a different search.' : 'Debit notes will appear here once issued.'}</p>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredNotes.map((note) => (
                      <TableRow key={note.id} className="hover:bg-gray-50 transition-colors">
                        <TableCell className="font-medium">{note.debitNoteNumber ?? '–'}</TableCell>
                        <TableCell className="font-medium">{note.creditNoteNumber ?? '–'}</TableCell>
                        <TableCell>{note.dealerName ?? note.dealerCode ?? '–'}</TableCell>
                        <TableCell>{note.form16aNumber ?? '–'}</TableCell>
                        <TableCell>{formatAmount(note.amount)}</TableCell>
                        <TableCell>{formatDate(note.issueDate)}</TableCell>
                        <TableCell>
                          <Badge
                            className={
                              note.status?.toLowerCase() === 'issued' || note.status?.toLowerCase() === 'completed'
                                ? 'bg-green-100 text-green-800 border-green-200'
                                : 'bg-gray-100 text-gray-700 border-gray-200'
                            }
                          >
                            {note.status ?? '–'}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex items-center justify-end gap-2">
                            {note.sapResponseAvailable ? (
                              <Button variant="outline" size="sm" onClick={() => openSapPreview(note)}>
                                <Eye className="w-4 h-4 mr-2" />
                                View
                              </Button>
                            ) : (
                              <Button variant="outline" size="sm" onClick={pullNow} disabled={pulling}>
                                {pulling ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
                                Pull
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

