import { useState, useCallback, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import {
  extractOcr,
  createForm16Submission,
  listDealerPendingQuarters,
  type Form16AExtractedData,
  type DealerPendingQuarterItem,
} from '@/services/form16Api';
import { toast } from 'sonner';
import {
  FileText,
  Loader2,
  CheckCircle2,
  AlertCircle,
  Info,
  ArrowLeft,
  Eye,
  Calendar,
} from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { UploadCard } from './components/UploadCard';

type Quarter = 'Q1' | 'Q2' | 'Q3' | 'Q4';

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

function displayValue(value: string | number | null | undefined): React.ReactNode {
  if (value === null || value === undefined || value === '') return <span className="text-gray-500 italic">N/A</span>;
  if (typeof value === 'number') return value.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return String(value);
}

function formatDeductorDetails(data: Form16AExtractedData | null): React.ReactNode {
  if (!data) return <span className="text-gray-500 italic">N/A</span>;
  const name = data.deductorName ?? data.nameAndAddressOfDeductor ?? null;
  const address = data.deductorAddress ?? null;
  const phone = data.deductorPhone ?? null;
  const email = data.deductorEmail ?? null;
  const na = <span className="text-gray-500 italic">N/A</span>;
  return (
    <>
      <p><span className="text-gray-500">Name: </span>{name ?? na}</p>
      <p><span className="text-gray-500">Address: </span>{address ?? na}</p>
      <p><span className="text-gray-500">Number: </span>{phone ?? na}</p>
      <p><span className="text-gray-500">Email: </span>{email ?? na}</p>
    </>
  );
}

export function Form16Submit() {
  const navigate = useNavigate();
  const [pendingQuarters, setPendingQuarters] = useState<DealerPendingQuarterItem[]>([]);
  const [pendingQuartersLoading, setPendingQuartersLoading] = useState(true);
  const [financialYear, setFinancialYear] = useState<string>('');
  const [quarter, setQuarter] = useState<Quarter | ''>('');
  const [file, setFile] = useState<File | null>(null);
  const [uploadState, setUploadState] = useState<'idle' | 'extracting' | 'success' | 'error'>('idle');
  const [extractedData, setExtractedData] = useState<Form16AExtractedData | null>(null);
  const [ocrProvider, setOcrProvider] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [manualTan, setManualTan] = useState('');
  const [manualDeductor, setManualDeductor] = useState('');
  const [pdfPreviewUrl, setPdfPreviewUrl] = useState<string | null>(null);
  const [showPdfPreview, setShowPdfPreview] = useState(false);

  useEffect(() => {
    let cancelled = false;
    listDealerPendingQuarters()
      .then((list) => { if (!cancelled) setPendingQuarters(Array.isArray(list) ? list : []); })
      .catch(() => { if (!cancelled) setPendingQuarters([]); })
      .finally(() => { if (!cancelled) setPendingQuartersLoading(false); });
    return () => { cancelled = true; };
  }, []);

  const openPdfPreview = useCallback(() => {
    if (!file) return;
    const url = URL.createObjectURL(file);
    setPdfPreviewUrl(url);
    setShowPdfPreview(true);
  }, [file]);

  const closePdfPreview = useCallback(() => {
    setShowPdfPreview(false);
    if (pdfPreviewUrl) {
      URL.revokeObjectURL(pdfPreviewUrl);
      setPdfPreviewUrl(null);
    }
  }, [pdfPreviewUrl]);

  const handleFileSelect = useCallback(async (selectedFile: File) => {
    if (!selectedFile.name.toLowerCase().endsWith('.pdf')) {
      toast.error('Please upload a PDF file');
      return;
    }
    setFile(selectedFile);
    setExtractedData(null);
    setOcrProvider(null);
    setUploadState('extracting');
    try {
      toast.loading('Extracting data with Google Gemini...', { id: 'form16-ocr' });
      const result = await extractOcr(selectedFile);
      setExtractedData(result.extractedData);
      setOcrProvider(result.ocrProvider || null);
      setManualTan(result.extractedData.tanNumber ?? result.extractedData.tanOfDeductor ?? '');
      setManualDeductor(result.extractedData.deductorName ?? result.extractedData.nameAndAddressOfDeductor ?? '');
      setFinancialYear(result.extractedData.financialYear ?? '');
      setQuarter((result.extractedData.quarter as Quarter) ?? '');
      setUploadState('success');
      toast.success(result.ocrProvider ? `Data extracted via ${result.ocrProvider}` : 'Data extracted', { id: 'form16-ocr' });
    } catch (err: unknown) {
      setUploadState('error');
      const message = err instanceof Error ? err.message : 'Failed to extract data from PDF';
      toast.error(message, { id: 'form16-ocr' });
    }
  }, []);

  const handleSubmit = async () => {
    if (!financialYear || !quarter) {
      toast.error('Financial year and quarter could not be extracted from the PDF. Please ensure you upload a valid Form 16A certificate.');
      return;
    }
    if (!file) {
      toast.error('Please upload Form 16A PDF');
      return;
    }
    const form16aNumber = (extractedData?.form16aNumber ?? '').trim() || `F16-${financialYear}-${quarter}-${Date.now()}`;
    const tdsAmount = extractedData?.tdsAmount ?? extractedData?.totalTaxDeducted ?? 0;
    const totalAmount = extractedData?.totalAmount ?? extractedData?.totalAmountPaid ?? 0;
    const tanNumber = (manualTan || (extractedData?.tanNumber ?? extractedData?.tanOfDeductor ?? '')).trim();
    const deductorName = (manualDeductor || (extractedData?.deductorName ?? extractedData?.nameAndAddressOfDeductor ?? '')).trim();
    if (!tanNumber || !deductorName) {
      toast.error('TAN and Deductor name are required. Please enter or correct them below.');
      return;
    }

    setIsSubmitting(true);
    try {
      const result = await createForm16Submission({
        financialYear,
        quarter,
        form16aNumber,
        tdsAmount: Number(tdsAmount) || 0,
        totalAmount: Number(totalAmount) || 0,
        tanNumber,
        deductorName,
        file,
        extractedData: extractedData ?? undefined,
      });
      const vStatus = result.validationStatus;
      const status =
        vStatus === 'success'
          ? ('success' as const)
          : vStatus === 'duplicate'
            ? ('duplicate' as const)
            : vStatus === 'failed'
              ? ('mismatch' as const)
              : ('error' as const);
      const duplicateMessage =
        status === 'duplicate'
          ? 'A credit note has already been issued for this financial year and quarter. This submission is recorded as a new version.'
          : undefined;
      const mismatchMessage =
        status === 'mismatch'
          ? (result.validationNotes || 'Form 16A details did not match with 26AS data.')
          : undefined;
      toast.success(status === 'success' ? 'Form 16A matched with 26AS. Credit note generated.' : 'Form 16A submitted successfully');
      navigate('/form16/submit/result', {
        state: {
          status,
          requestId: result.requestId,
          requestNumber: result.requestNumber,
          creditNoteNumber: result.creditNoteNumber ?? undefined,
          message: duplicateMessage ?? mismatchMessage,
        },
      });
    } catch (err: unknown) {
      const res = err && typeof err === 'object' && 'response' in err ? (err as { response?: { status?: number; data?: { message?: string } } }).response : undefined;
      const msg = res?.data?.message ?? (err instanceof Error ? err.message : 'Failed to submit');
      const isDuplicate = res?.status === 400 && (typeof msg === 'string' && (msg.toLowerCase().includes('duplicate') || msg.toLowerCase().includes('already exist')));
      if (isDuplicate) {
        navigate('/form16/submit/result', {
          state: {
            status: 'duplicate' as const,
            requestId: '',
            message: msg,
          },
        });
      } else {
        toast.error(String(msg));
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const showExtractedCard = Boolean(file);

  return (
    <div className="min-h-[80vh] w-full bg-gray-50 p-4 md:p-6">
      <div className="w-full max-w-7xl mx-auto space-y-6">
        {/* Header - always visible */}
        <div className="flex items-center gap-4">
          <Button type="button" variant="ghost" size="icon" onClick={() => navigate(-1)} aria-label="Go back">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Submit Form 16A</h1>
            <p className="text-sm text-gray-600">Upload your TDS certificate for credit reconciliation</p>
          </div>
        </div>

        {/* Quarters Pending Submission – same listing as Pending Submissions page */}
        <Card>
          <CardHeader>
            <CardTitle>Quarters Pending Submission</CardTitle>
            <CardDescription>
              These quarters don&apos;t have completed Form 16A submissions. Please submit Form 16A for these quarters.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="rounded-lg border overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow className="bg-gray-50">
                    <TableHead>Dealer Name</TableHead>
                    <TableHead>Financial Year</TableHead>
                    <TableHead>Quarter</TableHead>
                    <TableHead>Version</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>26AS start date</TableHead>
                    <TableHead>Days Status</TableHead>
                    <TableHead className="text-right">Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {pendingQuartersLoading ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-12 text-gray-500">
                        <Loader2 className="w-8 h-8 animate-spin mx-auto mb-2" />
                        <p>Loading...</p>
                      </TableCell>
                    </TableRow>
                  ) : pendingQuarters.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-12 text-gray-500">
                        <div className="flex flex-col items-center gap-2">
                          <FileText className="w-12 h-12 text-gray-300" />
                          <p>No pending submissions. All quarters are complete.</p>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : (
                    pendingQuarters.map((row) => (
                      <TableRow key={`${row.financial_year}|${row.quarter}`} className="hover:bg-gray-50">
                        <TableCell className="text-sm text-gray-900">{row.dealer_name ?? 'Your submission'}</TableCell>
                        <TableCell><span className="text-sm text-gray-900">FY {row.financial_year}</span></TableCell>
                        <TableCell>
                          <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">{row.quarter}</Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">
                            {row.has_submission ? 'V1' : '—'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className={
                            row.latest_submission_status === 'failed'
                              ? 'bg-red-50 text-red-700 border-red-200'
                              : row.has_submission
                                ? 'bg-slate-50 text-slate-600 border-slate-200'
                                : 'bg-gray-100 text-gray-600 border-gray-200'
                          }>
                            {row.latest_submission_status === 'failed' ? 'Failed' : row.has_submission ? 'Under review' : 'Not Submitted'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <Calendar className="w-4 h-4 text-gray-400" />
                            <span className="text-sm text-gray-700">{formatDate(row.twenty_six_as_start_date ?? row.audit_start_date)}</span>
                          </div>
                        </TableCell>
                        <TableCell>
                          {row.days_since_26as_uploaded != null && row.days_since_26as_uploaded >= 0 ? (
                            <span className="text-sm font-medium text-gray-700">due from {row.days_since_26as_uploaded} days</span>
                          ) : (
                            <span className="text-sm text-gray-500">—</span>
                          )}
                        </TableCell>
                        <TableCell className="text-right">
                          <Button size="sm" className="bg-teal-600 hover:bg-teal-700" onClick={() => navigate('/form16/submit')}>
                            Submit Now
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>

        {/* Upload - financial year and quarter are taken from OCR extraction */}
        <Card>
          <CardHeader>
            <CardTitle>Upload Form 16A Certificate</CardTitle>
            <CardDescription>PDF only. Financial year and quarter are taken from the certificate via OCR; no need to enter them manually.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <UploadCard
              state={uploadState === 'extracting' ? 'extracting' : uploadState === 'error' ? 'error' : uploadState === 'success' ? 'success' : 'idle'}
              onFileSelect={handleFileSelect}
              disabled={uploadState === 'extracting'}
            />
            {file && (
              <div className={`flex items-center justify-between p-3 rounded-lg border ${
                uploadState === 'extracting' ? 'bg-blue-50 border-blue-200' :
                uploadState === 'error' ? 'bg-red-50 border-red-200' : 'bg-green-50 border-green-200'
              }`}>
                <div className="flex items-center gap-2">
                  {uploadState === 'extracting' ? (
                    <Loader2 className="w-5 h-5 text-blue-600 shrink-0 animate-spin" />
                  ) : uploadState === 'error' ? (
                    <AlertCircle className="w-5 h-5 text-red-600 shrink-0" />
                  ) : (
                    <CheckCircle2 className="w-5 h-5 text-green-600 shrink-0" />
                  )}
                  <span className="text-sm font-medium">{file.name}</span>
                  <span className="text-xs text-gray-500">
                    {(file.size / 1024).toFixed(1)} KB
                    {uploadState === 'extracting' && ' • Extracting...'}
                    {uploadState === 'error' && ' • Extraction failed'}
                    {uploadState === 'success' && extractedData && ' • Data extracted'}
                  </span>
                </div>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    setFile(null);
                    setExtractedData(null);
                    setOcrProvider(null);
                    setManualTan('');
                    setManualDeductor('');
                    setFinancialYear('');
                    setQuarter('');
                    setUploadState('idle');
                    closePdfPreview();
                  }}
                  disabled={uploadState === 'extracting'}
                >
                  Remove
                </Button>
              </div>
            )}
            {file && (
              <Button
                type="button"
                variant="outline"
                className="w-full"
                onClick={openPdfPreview}
                disabled={uploadState === 'extracting'}
              >
                <Eye className="w-4 h-4 mr-2" />
                View Uploaded Form 16A
              </Button>
            )}
          </CardContent>
        </Card>

        {/* Important Notes – aligned with REform16 */}
        <Card className="border-blue-200 bg-blue-50">
          <CardHeader>
            <CardTitle className="text-blue-900 flex items-center gap-2">
              <Info className="w-5 h-5" />
              Important Notes
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-sm text-blue-800">
            <ul className="list-disc list-inside space-y-1 ml-2">
              <li>Ensure the Form 16A certificate is issued by the correct deductor (TAN and name must match)</li>
              <li>The certificate should match your Form 26AS data from the Income Tax portal</li>
              <li>If you submit multiple versions for the same quarter, only the latest approved version will be processed</li>
              <li>You can track all submissions in the Requests section (filter by Form 16)</li>
              <li>Processing typically takes 2–3 business days after validation</li>
            </ul>
          </CardContent>
        </Card>

        {/* Form 16A Extracted Details – below upload; main OCR fields only */}
        {showExtractedCard && (
          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <FileText className="w-5 h-5 text-blue-600" />
                <CardTitle>Form 16A Extracted Details</CardTitle>
              </div>
              <CardDescription>
                {uploadState === 'extracting'
                  ? 'Extracting with Google Gemini (or regex fallback)...'
                  : extractedData
                    ? (ocrProvider ? `Extracted via ${ocrProvider}. Unmapped fields show N/A.` : 'Certificate details extracted from uploaded document.')
                    : uploadState === 'error'
                      ? 'Extraction failed. You can remove the file and try again.'
                      : 'Waiting for extraction...'}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {uploadState === 'extracting' ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="w-8 h-8 text-blue-600 animate-spin mr-3" />
                  <p className="text-gray-600">Extracting data...</p>
                </div>
              ) : uploadState === 'error' ? (
                <div className="flex items-center justify-center py-8">
                  <AlertCircle className="w-8 h-8 text-amber-600 mr-3 shrink-0" />
                  <p className="text-gray-600">Data extraction failed. Please remove the file and try uploading again.</p>
                </div>
              ) : extractedData ? (
                <>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="md:col-span-2">
                      <p className="text-sm text-gray-500">Deductor details</p>
                      <div className="text-sm mt-1 font-medium space-y-0.5">
                        {formatDeductorDetails(extractedData)}
                      </div>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">TAN of the deductor</p>
                      <p className="text-sm mt-1 font-medium">{displayValue(extractedData.tanOfDeductor ?? extractedData.tanNumber)}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Total (Rs)</p>
                      <p className="text-sm mt-1 font-medium">
                        {(extractedData.totalAmountPaid ?? extractedData.totalAmount) != null
                          ? `₹ ${displayValue(extractedData.totalAmountPaid ?? extractedData.totalAmount)}`
                          : displayValue(null)}
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Total tax deducted</p>
                      <p className="text-sm mt-1 font-medium">
                        {(extractedData.totalTaxDeducted ?? extractedData.tdsAmount) != null
                          ? `₹ ${displayValue(extractedData.totalTaxDeducted ?? extractedData.tdsAmount)}`
                          : displayValue(null)}
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Total TDS deposited</p>
                      <p className="text-sm mt-1 font-medium">
                        {(extractedData.totalTdsDeposited ?? extractedData.tdsAmount) != null
                          ? `₹ ${displayValue(extractedData.totalTdsDeposited ?? extractedData.tdsAmount)}`
                          : displayValue(null)}
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Nature of payment</p>
                      <p className="text-sm mt-1 font-medium">{displayValue(extractedData.natureOfPayment)}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Transaction date</p>
                      <p className="text-sm mt-1 font-medium">{displayValue(extractedData.transactionDate)}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Status of matching with OLTAS</p>
                      <p className="text-sm mt-1 font-medium">{displayValue(extractedData.statusOfMatchingOltas)}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Date of booking</p>
                      <p className="text-sm mt-1 font-medium">{displayValue(extractedData.dateOfBooking)}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Form 16 Assessment Year</p>
                      <p className="text-sm mt-1 font-medium">{displayValue(extractedData.assessmentYear)}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Quarter</p>
                      <p className="text-sm mt-1 font-medium">{displayValue(extractedData.quarter)}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Certificate No / Form 16A No</p>
                      <p className="text-sm mt-1 font-medium">{displayValue(extractedData.form16aNumber)}</p>
                    </div>
                  </div>

                  <div className="border-t pt-4 space-y-4">
                    <p className="text-sm font-medium text-gray-700">Correct if needed (required for submit)</p>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="form16-tan">TAN of deductor *</Label>
                        <Input
                          id="form16-tan"
                          value={manualTan}
                          onChange={(e) => setManualTan(e.target.value)}
                          placeholder="e.g. BLRH07660C"
                          maxLength={10}
                        />
                      </div>
                      <div className="space-y-2 md:col-span-2">
                        <Label htmlFor="form16-deductor">Deductor name *</Label>
                        <Input
                          id="form16-deductor"
                          value={manualDeductor}
                          onChange={(e) => setManualDeductor(e.target.value)}
                          placeholder="Name and address of deductor"
                        />
                      </div>
                    </div>
                  </div>

                  <div className="flex items-start gap-2 p-3 bg-green-50 border border-green-200 rounded-lg">
                    <CheckCircle2 className="w-5 h-5 text-green-600 shrink-0 mt-0.5" />
                    <div className="text-sm text-green-800">
                      <p className="font-medium">Data extracted</p>
                      <p className="mt-1">
                        These values will be validated on submit. You can correct TAN and Deductor name above if needed.
                      </p>
                    </div>
                  </div>

                  <div className="flex justify-end gap-2 pt-2">
                    <Button type="button" variant="outline" onClick={() => navigate(-1)} disabled={isSubmitting}>
                      Cancel
                    </Button>
                    <Button
                      type="button"
                      className="bg-re-green hover:bg-re-green/90"
                      onClick={handleSubmit}
                      disabled={!financialYear || !quarter || isSubmitting}
                    >
                      {isSubmitting ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
                      Submit Form 16A
                    </Button>
                  </div>
                </>
              ) : null}
            </CardContent>
          </Card>
        )}

        {/* PDF Preview Dialog */}
        <Dialog open={showPdfPreview} onOpenChange={(open) => !open && closePdfPreview()}>
          <DialogContent className="max-w-4xl max-h-[90vh] flex flex-col" aria-describedby="form16-pdf-description">
            <DialogHeader>
              <DialogTitle>Form 16A Certificate</DialogTitle>
              <DialogDescription id="form16-pdf-description" className="sr-only">
                Preview of the uploaded Form 16A PDF certificate
              </DialogDescription>
            </DialogHeader>
            <div className="flex-1 min-h-0 rounded border bg-gray-100">
              {pdfPreviewUrl && (
                <iframe
                  title="Form 16A PDF"
                  src={pdfPreviewUrl}
                  className="w-full h-[70vh] rounded"
                />
              )}
            </div>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}
