/**
 * Form 16 Pending Submissions – Dealer only.
 * Shows quarters for which Form 16A has not been submitted or is pending/failed.
 * API-driven: listDealerPendingQuarters, listDealerSubmissions.
 */

import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { AlertTriangle, Calendar, FileText, Filter, X, ChevronDown, ChevronUp, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { listDealerSubmissions, listDealerPendingQuarters, type DealerPendingQuarterItem, type DealerPendingSubmissionItem } from '@/services/form16Api';
import { toast } from 'sonner';

export function Form16PendingSubmissions() {
  const navigate = useNavigate();
  const [pendingQuarters, setPendingQuarters] = useState<DealerPendingQuarterItem[]>([]);
  const [submissions, setSubmissions] = useState<DealerPendingSubmissionItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState({ financialYear: 'all', quarter: 'all' });

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      try {
        const [quartersRes, subsRes] = await Promise.all([
          listDealerPendingQuarters(),
          listDealerSubmissions({ status: 'pending,failed,completed' }),
        ]);
        if (!cancelled) {
          setPendingQuarters(Array.isArray(quartersRes) ? quartersRes : []);
          setSubmissions(Array.isArray(subsRes) ? subsRes : []);
        }
      } catch (e) {
        if (!cancelled) {
          toast.error('Failed to load pending submissions');
          setPendingQuarters([]);
          setSubmissions([]);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const filteredQuarters = pendingQuarters.filter((q) => {
    if (filters.financialYear !== 'all' && q.financial_year !== filters.financialYear) return false;
    if (filters.quarter !== 'all' && q.quarter !== filters.quarter) return false;
    return true;
  });

  const totalPending = filteredQuarters.length;
  const overdueCount = filteredQuarters.filter((q) => (q.days_overdue ?? 0) > 0).length;
  const upcomingCount = filteredQuarters.filter((q) => (q.days_remaining ?? 0) > 0).length;

  const clearFilters = () => setFilters({ financialYear: 'all', quarter: 'all' });
  const hasActiveFilters = filters.financialYear !== 'all' || filters.quarter !== 'all';

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

  const formatAmount = (amount: number | null | undefined) => {
    if (amount == null) return '—';
    return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(amount);
  };

  const getStatusBadgeVariant = (displayStatus: string | undefined) => {
    const s = (displayStatus || '').toLowerCase();
    if (s === 'completed') return 'bg-emerald-50 text-emerald-700 border-emerald-200';
    if (s === 'balance mismatch' || s === 'failed') return 'bg-red-50 text-red-700 border-red-200';
    if (s === 'resubmission needed' || s === 'duplicate' || s === 'duplicate submission') return 'bg-amber-50 text-amber-700 border-amber-200';
    return 'bg-slate-50 text-slate-600 border-slate-200';
  };

  const handleSubmitNow = (_quarter?: DealerPendingQuarterItem) => {
    navigate('/form16/submit');
  };

  const financialYearOptions = [...new Set(pendingQuarters.map((q) => q.financial_year))].sort();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Pending Submissions</h1>
          <p className="text-gray-600 mt-1">Quarters for which Form 16A has not been submitted.</p>
        </div>
        <div className="flex items-center gap-2">
          <Button className="bg-teal-600 hover:bg-teal-700" onClick={() => navigate('/form16/submit')}>
            New Submission
          </Button>
          <Button variant="outline" onClick={() => setShowFilters(!showFilters)} className="gap-2">
            <Filter className="w-4 h-4" />
            Filters
            {hasActiveFilters && (
              <Badge variant="default" className="ml-1 bg-teal-600 hover:bg-teal-700">
                {[filters.financialYear, filters.quarter].filter((v) => v !== 'all').length}
              </Badge>
            )}
            {showFilters ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
          </Button>
        </div>
      </div>

      {showFilters && (
        <Card>
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-base">Filter</CardTitle>
              {hasActiveFilters && (
                <Button variant="ghost" size="sm" onClick={clearFilters} className="gap-2 text-gray-600 hover:text-gray-900">
                  <X className="w-4 h-4" />
                  Clear All
                </Button>
              )}
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Financial Year</Label>
                <Select value={filters.financialYear} onValueChange={(v) => setFilters((f) => ({ ...f, financialYear: v }))}>
                  <SelectTrigger><SelectValue placeholder="All years" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Years</SelectItem>
                    {financialYearOptions.map((y) => (
                      <SelectItem key={y} value={y}>{y}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Quarter</Label>
                <Select value={filters.quarter} onValueChange={(v) => setFilters((f) => ({ ...f, quarter: v }))}>
                  <SelectTrigger><SelectValue placeholder="All quarters" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Quarters</SelectItem>
                    <SelectItem value="Q1">Q1</SelectItem>
                    <SelectItem value="Q2">Q2</SelectItem>
                    <SelectItem value="Q3">Q3</SelectItem>
                    <SelectItem value="Q4">Q4</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {overdueCount > 0 && (
        <Card className="border-red-200 bg-red-50">
          <CardContent className="p-4">
            <div className="flex items-start gap-3">
              <AlertTriangle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
              <p className="text-sm text-red-800">
                <span className="font-semibold">{overdueCount} overdue submission{overdueCount > 1 ? 's' : ''} detected.</span>
                Please submit Form 16A immediately to avoid penalties.
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500 mb-1">Total Pending</p>
                <p className="text-2xl font-semibold text-gray-900">{totalPending}</p>
              </div>
              <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center">
                <FileText className="w-6 h-6 text-gray-600" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500 mb-1">Overdue</p>
                <p className="text-2xl font-semibold text-red-600">{overdueCount}</p>
              </div>
              <div className="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                <AlertTriangle className="w-6 h-6 text-red-600" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500 mb-1">Upcoming</p>
                <p className="text-2xl font-semibold text-amber-600">{upcomingCount}</p>
              </div>
              <div className="w-12 h-12 bg-amber-100 rounded-lg flex items-center justify-center">
                <Calendar className="w-6 h-6 text-amber-600" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Pending Form 16A Submissions</CardTitle>
          <CardDescription>Complete list of quarters awaiting submission.</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>
                {loading ? (
                  <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>
                ) : filteredQuarters.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>{hasActiveFilters ? 'No quarters match your filters' : 'No pending submissions'}</p>
                        {hasActiveFilters && (
                          <Button variant="outline" size="sm" onClick={clearFilters} className="mt-2">Clear Filters</Button>
                        )}
                        {!hasActiveFilters && (
                          <Button size="sm" className="bg-teal-600 hover:bg-teal-700 mt-2" onClick={() => navigate('/form16/submit')}>
                            New Submission
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredQuarters.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={() => handleSubmitNow(row)}>
                          Submit Now
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Your Form 16 Submissions</CardTitle>
          <CardDescription>Requests you have submitted. Total amount and credit note (when issued) are shown. Status is never shown as Pending.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="rounded-lg border overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow className="bg-gray-50">
                  <TableHead>Request ID</TableHead>
                  <TableHead>Financial Year</TableHead>
                  <TableHead>Quarter</TableHead>
                  <TableHead className="text-right">Total Amount</TableHead>
                  <TableHead>Credit Note No.</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Submitted</TableHead>
                  <TableHead className="text-right">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-8 text-gray-500">
                      <Loader2 className="w-6 h-6 animate-spin mx-auto" />
                    </TableCell>
                  </TableRow>
                ) : submissions.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-8 text-gray-500">
                      No Form 16 submissions yet. Use &quot;New Submission&quot; to submit.
                    </TableCell>
                  </TableRow>
                ) : (
                  submissions.map((row) => (
                    <TableRow key={row.id} className="hover:bg-gray-50">
                      <TableCell className="font-mono text-sm">{row.requestId ? String(row.requestId).slice(0, 8) + '…' : '—'}</TableCell>
                      <TableCell>FY {row.financial_year}</TableCell>
                      <TableCell><Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">{row.quarter}</Badge></TableCell>
                      <TableCell className="text-right font-medium">{formatAmount(row.total_amount)}</TableCell>
                      <TableCell>{row.credit_note_number ?? '—'}</TableCell>
                      <TableCell>
                        <Badge variant="outline" className={getStatusBadgeVariant(row.display_status)}>
                          {row.display_status ?? (row.status === 'completed' ? 'Completed' : row.status === 'failed' ? 'Failed' : 'Under review')}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-sm text-gray-600">{formatDate(row.submitted_date)}</TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => navigate(`/request/${row.requestId}`)}
                        >
                          View Request
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {pendingQuarters.length > 0 && (
        <Card className="border-amber-200 bg-amber-50/50">
          <CardHeader>
            <CardTitle className="text-amber-900">Quarters Pending Submission</CardTitle>
            <CardDescription className="text-amber-700">
              These quarters don&apos;t have completed Form 16A submissions. Please submit Form 16A for these quarters.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
              {pendingQuarters.slice(0, 8).map((pq) => (
                <div key={`${pq.financial_year}|${pq.quarter}`} className="p-3 bg-white rounded-lg border border-amber-200">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-semibold text-gray-900">{pq.quarter}</p>
                      <p className="text-sm text-gray-600">{pq.financial_year}</p>
                      {pq.has_submission && pq.latest_submission_status && (
                        <Badge variant="outline" className={`mt-1 text-xs ${
                          pq.latest_submission_status === 'failed'
                            ? 'bg-red-50 text-red-700 border-red-200'
                            : 'bg-slate-50 text-slate-600 border-slate-200'
                        }`}>
                          {pq.latest_submission_status === 'failed' ? 'Failed' : 'Under review'}
                        </Badge>
                      )}
                    </div>
                    <Button size="sm" className="bg-teal-600 hover:bg-teal-700" onClick={() => navigate('/form16/submit')}>
                      Submit
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
