import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
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 { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { ArrowLeft, Mail, Download, Loader2, RefreshCw, FileText, IndianRupee, CalendarClock } from 'lucide-react';
import { getCreditNoteById, getCreditNoteSapResponse, type CreditNoteDetailResponse, type Form16SapResponseRecord } from '@/services/form16Api';
import { toast } from 'sonner';

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 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 || '',
  };
}

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;
  }
}

export function Form16CreditNoteDetail() {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [data, setData] = useState<CreditNoteDetailResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [pulling, setPulling] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [previewRow, setPreviewRow] = useState<Record<string, string> | null>(null);
  const [previewDownloadUrl, setPreviewDownloadUrl] = useState<string | null>(null);

  useEffect(() => {
    const numId = id ? parseInt(id, 10) : NaN;
    if (Number.isNaN(numId)) {
      setLoading(false);
      return;
    }
    let cancelled = false;
    getCreditNoteById(numId)
      .then((res) => {
        if (!cancelled) setData(res);
      })
      .catch((err) => {
        if (!cancelled) {
          toast.error(err instanceof Error ? err.message : 'Failed to load credit note');
          navigate('/form16/credit-notes');
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [id, navigate]);

  const handleResend = () => {
    toast.info('Resend to dealer – integration pending');
  };

  const handlePull = async () => {
    const numId = id ? parseInt(id, 10) : NaN;
    if (Number.isNaN(numId)) return;
    setPulling(true);
    try {
      const res = await getCreditNoteById(numId);
      setData(res);
      if (res.creditNote?.sapResponseAvailable) toast.success('Credit note is available to download.');
      else toast.info('Credit note is being generated. Please wait.');
    } catch (e: any) {
      toast.error(e instanceof Error ? e.message : 'Failed to pull credit note');
    } finally {
      setPulling(false);
    }
  };

  const handleDownload = async () => {
    const numId = id ? parseInt(id, 10) : NaN;
    if (Number.isNaN(numId)) return;
    try {
      setPreviewOpen(true);
      setPreviewLoading(true);
      setPreviewRow(null);
      setPreviewDownloadUrl(null);
      const payload = await getCreditNoteSapResponse(numId);
      const row = mapSapResponseToPreviewRow(payload.sapResponse);
      setPreviewRow(row);
      setPreviewDownloadUrl(payload.url || null);
    } catch (e: any) {
      const msg =
        e?.response?.status === 409
          ? 'The credit note is being generated, wait.'
          : (e instanceof Error ? e.message : 'Failed to download');
      toast.error(String(msg));
    } finally {
      setPreviewLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 p-4 md:p-6 flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-teal-600" />
      </div>
    );
  }

  if (!data) {
    return null;
  }

  const { creditNote, dealerName, dealerEmail, dealerContact, dealerCreditNotes } = data;
  const cnNum = creditNote.creditNoteNumber
    ? creditNote.creditNoteNumber.startsWith('CN')
      ? creditNote.creditNoteNumber
      : `CN #${creditNote.creditNoteNumber}`
    : '–';

  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);
            setPreviewDownloadUrl(null);
          }
        }}
      >
        <DialogContent className="sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>SAP Response</DialogTitle>
            <DialogDescription>
              {previewLoading ? 'Loading SAP response CSV…' : 'Review SAP response details and download the CSV.'}
            </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">
              {/* Card 1 (GREEN): SAP identifiers only */}
              <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>

              {/* Card 2: Details */}
              <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">Credit 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">{formatAmount(creditNote.amount)}</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">{formatIssuedAt(creditNote.issueDate)}</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>
            <Button
              onClick={() => {
                if (!previewDownloadUrl) {
                  toast.error('CSV download link not available');
                  return;
                }
                window.open(previewDownloadUrl, '_blank');
              }}
              disabled={!previewRow || previewLoading || !previewDownloadUrl}
            >
              <Download className="w-4 h-4 mr-2" />
              Download CSV
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <div className="w-full min-w-0">
        <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => navigate('/form16/credit-notes')}
            className="text-gray-600 hover:text-gray-900"
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to Credit Notes
          </Button>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={handleResend}>
              <Mail className="w-4 h-4 mr-2" />
              Resend to Dealer
            </Button>
          </div>
        </div>

        {/* Main Credit Note Card */}
        <Card className="mb-6">
          <CardContent className="pt-6">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <div className="flex items-center gap-2 flex-wrap mb-1">
                  <span className="text-xl font-semibold text-gray-900">{cnNum}</span>
                  <Badge className="bg-green-100 text-green-800 border-green-200">
                    {creditNote.status ?? 'Issued'}
                  </Badge>
                </div>
                <p className="text-sm text-gray-500">
                  Issued on {formatDate(creditNote.issueDate)}
                </p>
              </div>
              <div className="text-right">
                <p className="text-sm text-gray-500">Credit Amount</p>
                <p className="text-2xl font-semibold text-green-600">
                  {formatAmount(creditNote.amount)}
                </p>
              </div>
            </div>

            <div className="flex justify-end gap-2 mt-4">
              {creditNote.sapResponseAvailable ? (
                <Button variant="outline" size="sm" onClick={handleDownload}>
                  <Download className="w-4 h-4 mr-2" />
                  Download Credit Note
                </Button>
              ) : (
                <Button variant="outline" size="sm" onClick={handlePull} disabled={pulling}>
                  {pulling ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
                  Pull Credit Note
                </Button>
              )}
            </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-6 pt-6 border-t border-gray-100">
              <div>
                <p className="text-xs text-gray-500 uppercase tracking-wide">Dealer Name</p>
                <p className="text-sm font-medium text-gray-900">{dealerName || '–'}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500 uppercase tracking-wide">Form 16A Number</p>
                <p className="text-sm font-medium text-gray-900">{creditNote.submission?.form16aNumber ?? '–'}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500 uppercase tracking-wide">Email</p>
                <p className="text-sm text-gray-700">{dealerEmail || '–'}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500 uppercase tracking-wide">Contact</p>
                <p className="text-sm text-gray-700">{dealerContact || '–'}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Dealer Transaction History */}
        <Card>
          <CardHeader>
            <CardTitle>Dealer Transaction History</CardTitle>
            <CardDescription>All credit notes issued to {dealerName || 'this dealer'}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="rounded-lg border overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Submission Date</TableHead>
                    <TableHead>Form 16A No.</TableHead>
                    <TableHead>Amount</TableHead>
                    <TableHead>Credit Note Issued</TableHead>
                    <TableHead>Credit Note No.</TableHead>
                    <TableHead>CN Issue Date</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {dealerCreditNotes.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                        No other credit notes for this dealer
                      </TableCell>
                    </TableRow>
                  ) : (
                    dealerCreditNotes.map((cn) => (
                      <TableRow key={cn.id} className="hover:bg-gray-50 transition-colors">
                        <TableCell>{formatDate(cn.submittedDate)}</TableCell>
                        <TableCell>{cn.form16aNumber ?? '–'}</TableCell>
                        <TableCell>{formatAmount(cn.amount)}</TableCell>
                        <TableCell>
                          <Badge className="bg-green-100 text-green-800 border-green-200">Yes</Badge>
                        </TableCell>
                        <TableCell>
                            {cn.creditNoteNumber
                              ? cn.creditNoteNumber.startsWith('CN')
                                ? cn.creditNoteNumber
                                : `CN #${cn.creditNoteNumber}`
                              : '–'}
                          </TableCell>
                        <TableCell>{formatDate(cn.issueDate)}</TableCell>
                        <TableCell>
                          <Badge
                            className={
                              cn.status?.toLowerCase() === 'withdrawn'
                                ? 'bg-red-50 text-red-700 border-red-200'
                                : 'bg-green-100 text-green-800 border-green-200'
                            }
                          >
                            {cn.status?.toLowerCase() === 'withdrawn' ? 'Withdrawn' : 'Completed'}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
