import { useState, useEffect, useCallback, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Filter,
  X,
  ChevronDown,
  ChevronUp,
  Download,
  Upload,
  FileText,
  Loader2,
  Search,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react';
import { Progress } from '@/components/ui/progress';
import {
  list26asEntries,
  upload26asFile,
  get26asUploadHistory,
  type Tds26asEntryItem,
  type List26asParams,
  type List26asSummary,
  type Form1626asUploadHistoryItem,
} from '@/services/form16Api';
import { toast } from 'sonner';

const PAGE_SIZE = 50;
const QUARTERS = ['Q1', 'Q2', 'Q3', 'Q4'];
const SECTIONS = [
  { value: '194A', label: '194A - Interest' },
  { value: '194C', label: '194C - Contractor' },
  { value: '194J', label: '194J - Professional' },
  { value: '194H', label: '194H - Commission' },
  { value: '194Q', label: '194Q' },
  { value: '206CH', label: '206CH' },
];

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

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

function generateFinancialYears(): string[] {
  const y = new Date().getFullYear();
  const out: string[] = [];
  for (let i = 0; i < 6; i++) {
    const start = y - i;
    const end = (start + 1).toString().slice(-2);
    out.push(`${start}-${end}`);
  }
  return out;
}

function getStatusBadge(status: string | null | undefined) {
  const s = (status || '').trim().toUpperCase().slice(0, 1);
  switch (s) {
    case 'F':
      return (
        <Badge className="bg-green-100 text-green-700 border-green-300">
          F
        </Badge>
      );
    case 'O':
      return (
        <Badge className="bg-orange-100 text-orange-700 border-orange-300">
          O
        </Badge>
      );
    case 'M':
      return (
        <Badge className="bg-blue-100 text-blue-700 border-blue-300">
          M
        </Badge>
      );
    case 'U':
      return (
        <Badge className="bg-red-100 text-red-700 border-red-300">
          U
        </Badge>
      );
    case 'P':
      return (
        <Badge className="bg-amber-100 text-amber-700 border-amber-300">
          P
        </Badge>
      );
    default:
      return status ? (
        <Badge variant="secondary">{status}</Badge>
      ) : null;
  }
}

type FilterStatus = 'all' | 'F' | 'O' | 'P';

export function Form16_26AS() {
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState({
    assessmentYear: 'all',
    quarter: 'all',
    section: 'all',
    deductor: '',
    status: 'all' as FilterStatus,
  });
  const [searchInput, setSearchInput] = useState('');
  const searchDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [showUploadDialog, setShowUploadDialog] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [processingProgress, setProcessingProgress] = useState(0);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const processingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const [entries, setEntries] = useState<Tds26asEntryItem[]>([]);
  const [total, setTotal] = useState(0);
  const [summary, setSummary] = useState<List26asSummary>({
    totalRecords: 0,
    booked: 0,
    notBooked: 0,
    pending: 0,
    totalTaxDeducted: 0,
  });
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);

  const [uploadHistory, setUploadHistory] = useState<Form1626asUploadHistoryItem[]>([]);
  const [loadingHistory, setLoadingHistory] = useState(false);

  const financialYears = generateFinancialYears();

  const fetchUploadHistory = useCallback(async () => {
    try {
      setLoadingHistory(true);
      const history = await get26asUploadHistory(50);
      setUploadHistory(history);
    } catch (err) {
      console.error('[Form16_26AS] upload history', err);
      setUploadHistory([]);
    } finally {
      setLoadingHistory(false);
    }
  }, []);

  const fetchEntries = useCallback(
    async (pageIndex: number = 0) => {
      try {
        setLoading(true);
        const params: List26asParams = {
          limit: PAGE_SIZE,
          offset: pageIndex * PAGE_SIZE,
        };
        if (filters.assessmentYear !== 'all') {
          params.financialYear = filters.assessmentYear;
        }
        if (filters.quarter !== 'all') params.quarter = filters.quarter;
        if (filters.section !== 'all') params.sectionCode = filters.section;
        if (filters.deductor.trim()) params.search = filters.deductor.trim();
        if (filters.status !== 'all') params.status = filters.status;

        const result = await list26asEntries(params);
        setEntries(result.entries);
        setTotal(result.total);
        setSummary(result.summary);
        setPage(pageIndex);
      } catch (err: unknown) {
        console.error('[Form16_26AS]', err);
        toast.error(err instanceof Error ? err.message : 'Failed to load 26AS entries');
        setEntries([]);
        setTotal(0);
        setSummary({
          totalRecords: 0,
          booked: 0,
          notBooked: 0,
          pending: 0,
          totalTaxDeducted: 0,
        });
      } finally {
        setLoading(false);
      }
    },
    [filters.assessmentYear, filters.quarter, filters.section, filters.deductor, filters.status]
  );

  useEffect(() => {
    fetchEntries(0);
  }, [fetchEntries]);

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

  useEffect(() => {
    if (searchDebounceRef.current) clearTimeout(searchDebounceRef.current);
    searchDebounceRef.current = setTimeout(() => {
      setFilters((f) => ({ ...f, deductor: searchInput.trim() }));
    }, 300);
    return () => {
      if (searchDebounceRef.current) clearTimeout(searchDebounceRef.current);
    };
  }, [searchInput]);

  useEffect(() => {
    return () => {
      if (processingIntervalRef.current) {
        clearInterval(processingIntervalRef.current);
        processingIntervalRef.current = null;
      }
    };
  }, []);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (file.size > 50 * 1024 * 1024) {
        toast.error('File size must be less than 50MB');
        return;
      }
      if (!file.name.toLowerCase().endsWith('.txt')) {
        toast.error('Only .txt files are supported');
        return;
      }
      setSelectedFile(file);
    }
  };

  const handleUpload = async () => {
    if (!selectedFile) {
      toast.error('Please select a file');
      return;
    }
    setUploading(true);
    setUploadProgress(0);
    setProcessingProgress(0);
    if (processingIntervalRef.current) {
      clearInterval(processingIntervalRef.current);
      processingIntervalRef.current = null;
    }
    try {
      const result = await upload26asFile(selectedFile, (p) => {
        setUploadProgress(p);
        if (p >= 100 && !processingIntervalRef.current) {
          setProcessingProgress(0);
          let tick = 0;
          processingIntervalRef.current = setInterval(() => {
            tick += 1;
            setProcessingProgress((prev) => Math.min(99, prev + 4 + Math.floor(tick / 3)));
          }, 300);
        }
      });
      if (processingIntervalRef.current) {
        clearInterval(processingIntervalRef.current);
        processingIntervalRef.current = null;
      }
      setProcessingProgress(100);
      if (result.imported > 0) {
        toast.success(
          `Successfully imported ${result.imported} entries.${result.errors?.length ? ` ${result.errors.length} warnings.` : ''}`
        );
        setShowUploadDialog(false);
        setSelectedFile(null);
        if (fileInputRef.current) fileInputRef.current.value = '';
        fetchEntries(0);
        fetchUploadHistory();
      } else if (result.errors?.length) {
        toast.error(result.errors[0] || 'Upload failed');
      }
    } catch (err: unknown) {
      if (processingIntervalRef.current) {
        clearInterval(processingIntervalRef.current);
        processingIntervalRef.current = null;
      }
      toast.error(err instanceof Error ? err.message : 'Upload failed');
    } finally {
      setUploading(false);
      setUploadProgress(0);
      setProcessingProgress(0);
    }
  };

  const clearFilters = () => {
    setFilters({
      assessmentYear: 'all',
      quarter: 'all',
      section: 'all',
      deductor: '',
      status: 'all',
    });
    setSearchInput('');
  };

  const hasActiveFilters =
    filters.assessmentYear !== 'all' ||
    filters.quarter !== 'all' ||
    filters.section !== 'all' ||
    filters.deductor !== '' ||
    filters.status !== 'all';

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
  const canPrev = page > 0;
  const canNext = page < totalPages - 1;
  // Page numbers to show (sliding window of up to 9)
  const paginationStart = Math.max(0, Math.min(page - 4, totalPages - 9));
  const paginationEnd = Math.min(totalPages - 1, paginationStart + 8);
  const pageNumbers = Array.from(
    { length: paginationEnd - paginationStart + 1 },
    (_, i) => paginationStart + i
  );

  return (
    <div className="min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden">
      <div className="w-full max-w-[98vw] xl:max-w-[1920px] mx-auto space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h2 className="text-2xl font-semibold text-gray-900 mb-1">Form 26AS - TDS Data</h2>
            <p className="text-gray-600 text-sm">View and manage TDS deduction records from Form 26AS</p>
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <div className="relative flex-1 min-w-[180px] max-w-[280px]">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                placeholder="Search..."
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                className="pl-9 h-9"
              />
            </div>
            <Button
              onClick={() => setShowUploadDialog(true)}
              className="gap-2 bg-teal-600 hover:bg-teal-700 text-white"
            >
              <Upload className="w-4 h-4" />
              Upload 26AS File
            </Button>
            <Button
              variant="outline"
              onClick={() => setShowFilters(!showFilters)}
              className="gap-2"
            >
              <Filter className="w-4 h-4" />
              Filters
              {hasActiveFilters && (
                <Badge className="ml-1 bg-teal-600 hover:bg-teal-700 text-white">
                  {[filters.assessmentYear, filters.quarter, filters.section, filters.deductor, filters.status].filter(
                    (v) => v !== '' && v !== 'all'
                  ).length}
                </Badge>
              )}
              {showFilters ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
            </Button>
          </div>
        </div>

        {/* Upload Dialog */}
        <Dialog open={showUploadDialog} onOpenChange={setShowUploadDialog}>
          <DialogContent className="max-w-md">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Upload className="w-5 h-5" />
                Upload 26AS Data File
              </DialogTitle>
              <p className="text-sm text-muted-foreground">
                Upload a 26AS text file (.txt) to import TDS data. Large files will be processed in batches.
              </p>
            </DialogHeader>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="file-upload">Select 26AS File</Label>
                <div className="flex items-center gap-4">
                  <input
                    ref={fileInputRef}
                    id="file-upload"
                    type="file"
                    accept=".txt"
                    onChange={handleFileSelect}
                    disabled={uploading}
                    className="hidden"
                  />
                  <Button
                    variant="outline"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={uploading}
                    className="gap-2"
                  >
                    <FileText className="w-4 h-4" />
                    Choose File
                  </Button>
                  {selectedFile && (
                    <span className="text-sm text-gray-700 truncate">
                      {selectedFile.name} ({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)
                    </span>
                  )}
                </div>
              </div>
              {uploading && (
                <div className="space-y-5">
                  {/* Phase 1: Uploading file to server */}
                  <div className="space-y-2">
                    <p className="text-sm font-medium text-foreground">1. Uploading file to server</p>
                    <div className="flex justify-between text-sm text-muted-foreground">
                      <span>Sending your file to the server</span>
                      <span>{Math.round(uploadProgress)}%</span>
                    </div>
                    <Progress value={uploadProgress} className="h-2" />
                  </div>
                  {/* Phase 2: Processing & saving to database (after upload reaches 100%) */}
                  {uploadProgress >= 100 && (
                    <div className="space-y-2">
                      <p className="text-sm font-medium text-foreground">2. Processing & saving to database</p>
                      <div className="flex justify-between text-sm text-muted-foreground">
                        <span>Parsing 26AS data and saving TDS records</span>
                        <span>{Math.round(processingProgress)}%</span>
                      </div>
                      <Progress value={processingProgress} className="h-2" indicatorClassName="bg-teal-600" />
                    </div>
                  )}
                </div>
              )}
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setShowUploadDialog(false);
                  setSelectedFile(null);
                  if (fileInputRef.current) fileInputRef.current.value = '';
                }}
                disabled={uploading}
              >
                Cancel
              </Button>
              <Button
                onClick={handleUpload}
                disabled={!selectedFile || uploading}
                className="bg-teal-600 hover:bg-teal-700 gap-2"
              >
                {uploading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Uploading...
                  </>
                ) : (
                  <>
                    <Upload className="w-4 h-4" />
                    Upload
                  </>
                )}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Management – 26AS upload history */}
        <Card>
          <CardHeader>
            <CardTitle>Management</CardTitle>
            <CardDescription>
              History of 26AS file uploads: when and which user added or uploaded 26AS data
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="rounded-lg border overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Date &amp; Time</TableHead>
                    <TableHead>User</TableHead>
                    <TableHead>File Name</TableHead>
                    <TableHead className="text-right">Records Imported</TableHead>
                    <TableHead className="text-right">Errors</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loadingHistory ? (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center py-8">
                        <Loader2 className="w-6 h-6 animate-spin mx-auto text-teal-600" />
                        <p className="text-sm text-gray-500 mt-2">Loading upload history...</p>
                      </TableCell>
                    </TableRow>
                  ) : uploadHistory.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center py-8 text-gray-500">
                        No upload history yet. Uploads will appear here after you add a 26AS file.
                      </TableCell>
                    </TableRow>
                  ) : (
                    uploadHistory.map((row) => (
                      <TableRow key={row.id} className="hover:bg-gray-50">
                        <TableCell className="text-sm whitespace-nowrap">
                          {row.uploadedAt
                            ? new Date(row.uploadedAt).toLocaleString('en-IN', {
                                day: '2-digit',
                                month: 'short',
                                year: 'numeric',
                                hour: '2-digit',
                                minute: '2-digit',
                              })
                            : '–'}
                        </TableCell>
                        <TableCell className="text-sm">
                          {row.uploadedByDisplayName || row.uploadedByEmail || row.uploadedBy || '–'}
                        </TableCell>
                        <TableCell className="text-sm text-gray-600 max-w-[200px] truncate" title={row.fileName || undefined}>
                          {row.fileName || '–'}
                        </TableCell>
                        <TableCell className="text-right font-medium">{row.recordsImported}</TableCell>
                        <TableCell className="text-right">{row.errorsCount > 0 ? row.errorsCount : '–'}</TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>

        {/* Filter Panel */}
        {showFilters && (
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>Filter TDS Records</CardTitle>
                {hasActiveFilters && (
                  <Button variant="ghost" size="sm" onClick={clearFilters} className="gap-2 text-gray-600">
                    <X className="w-4 h-4" />
                    Clear All
                  </Button>
                )}
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                <div className="space-y-2">
                  <Label>Assessment Year</Label>
                  <Select
                    value={filters.assessmentYear}
                    onValueChange={(v) => setFilters((f) => ({ ...f, assessmentYear: v }))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select year" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Years</SelectItem>
                      {financialYears.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="Select quarter" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Quarters</SelectItem>
                      {QUARTERS.map((q) => (
                        <SelectItem key={q} value={q}>
                          {q}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Section</Label>
                  <Select
                    value={filters.section}
                    onValueChange={(v) => setFilters((f) => ({ ...f, section: v }))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select section" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Sections</SelectItem>
                      {SECTIONS.map((s) => (
                        <SelectItem key={s.value} value={s.value}>
                          {s.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Deductor</Label>
                  <Input
                    placeholder="Search deductor..."
                    value={filters.deductor}
                    onChange={(e) => setFilters((f) => ({ ...f, deductor: e.target.value }))}
                    className="h-9"
                  />
                </div>
                <div className="space-y-2">
                  <Label>Status</Label>
                  <Select
                    value={filters.status}
                    onValueChange={(v) => setFilters((f) => ({ ...f, status: v as FilterStatus }))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Status</SelectItem>
                      <SelectItem value="F">F – Final (Booked)</SelectItem>
                      <SelectItem value="O">O – Overbooked</SelectItem>
                      <SelectItem value="P">P – Pending</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Summary Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>Total Records</CardDescription>
              <CardTitle className="text-2xl">{summary.totalRecords}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>Booked</CardDescription>
              <CardTitle className="text-2xl text-green-600">{summary.booked}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>Not Booked</CardDescription>
              <CardTitle className="text-2xl text-red-600">{summary.notBooked}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>Pending</CardDescription>
              <CardTitle className="text-2xl text-amber-600">{summary.pending}</CardTitle>
            </CardHeader>
          </Card>
          <Card className="lg:col-span-1">
            <CardHeader className="pb-3">
              <CardDescription>Total Tax Deducted</CardDescription>
              <CardTitle className="text-xl">{formatCurrency(summary.totalTaxDeducted)}</CardTitle>
            </CardHeader>
          </Card>
        </div>

        {/* TDS Data Table */}
        <Card>
          <CardHeader>
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
              <div>
                <CardTitle>TDS Records from Form 26AS</CardTitle>
                <CardDescription>
                  {hasActiveFilters
                    ? `Showing ${entries.length} of ${total} records`
                    : `Complete list of TDS deduction records (${total} total)`}
                </CardDescription>
              </div>
              <Button variant="outline" size="sm" disabled>
                <Download className="w-4 h-4 mr-2" />
                Export
              </Button>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            <div
              className="overflow-auto min-h-[320px]"
              style={{ maxHeight: 'calc(100vh - 380px)' }}
            >
              <Table>
                <TableHeader>
                  <TableRow className="bg-gray-50">
                    <TableHead className="w-14">Sr No</TableHead>
                    <TableHead className="min-w-[180px]">Name of Deductor</TableHead>
                    <TableHead className="text-right min-w-[110px]">Total Amount Paid</TableHead>
                    <TableHead className="text-right min-w-[110px]">Total Tax Deducted</TableHead>
                    <TableHead className="text-right min-w-[110px]">Total TDS Deposited</TableHead>
                    <TableHead className="min-w-[100px]">TAN of Deductor</TableHead>
                    <TableHead className="min-w-[72px]">Section</TableHead>
                    <TableHead className="min-w-[64px]">Quarter</TableHead>
                    <TableHead className="min-w-[90px]">Assessment Year</TableHead>
                    <TableHead className="min-w-[90px]">Financial Year</TableHead>
                    <TableHead className="min-w-[100px]">Transaction Date</TableHead>
                    <TableHead className="min-w-[64px]">Status</TableHead>
                    <TableHead className="min-w-[100px]">Date of Booking</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading ? (
                    <TableRow>
                      <TableCell colSpan={13} className="text-center py-12">
                        <div className="flex flex-col items-center gap-2">
                          <Loader2 className="w-6 h-6 animate-spin text-teal-600" />
                          <p className="text-gray-500">Loading 26AS data...</p>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : entries.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={13} className="text-center py-12 text-gray-500">
                        {hasActiveFilters ? 'No records match your filters' : 'No TDS records found. Upload a 26AS file to get started.'}
                        {hasActiveFilters && (
                          <Button variant="outline" size="sm" onClick={clearFilters} className="mt-2">
                            Clear Filters
                          </Button>
                        )}
                      </TableCell>
                    </TableRow>
                  ) : (
                    entries.map((entry, idx) => (
                      <TableRow key={entry.id} className="hover:bg-gray-50">
                        <TableCell className="text-center text-sm text-gray-900">
                          {page * PAGE_SIZE + idx + 1}
                        </TableCell>
                        <TableCell className="text-sm text-gray-900">{entry.deductorName || '–'}</TableCell>
                        <TableCell className="text-right text-sm text-gray-900">
                          {formatCurrency(entry.amountPaid ?? 0)}
                        </TableCell>
                        <TableCell className="text-right text-sm text-gray-900">
                          {formatCurrency(entry.taxDeducted)}
                        </TableCell>
                        <TableCell className="text-right text-sm text-gray-900">
                          {formatCurrency(entry.totalTdsDeposited ?? 0)}
                        </TableCell>
                        <TableCell className="text-sm text-gray-700 font-mono">{entry.tanNumber}</TableCell>
                        <TableCell>
                          <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
                            {entry.sectionCode || '–'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">
                            {entry.quarter}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-sm text-gray-700 font-medium">
                          {entry.assessmentYear || '–'}
                        </TableCell>
                        <TableCell className="text-sm text-gray-700 font-medium">
                          {entry.financialYear || '–'}
                        </TableCell>
                        <TableCell className="text-sm text-gray-700">
                          {formatDate(entry.transactionDate)}
                        </TableCell>
                        <TableCell>{getStatusBadge(entry.statusOltas)}</TableCell>
                        <TableCell className="text-sm text-gray-700">
                          {formatDate(entry.dateOfBooking)}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>

            {/* Pagination */}
            {!loading && total > PAGE_SIZE && (
              <div className="flex items-center justify-between mt-4 px-6 pb-6">
                <p className="text-sm text-gray-600">
                  Page {page + 1} of {totalPages} ({total} records)
                </p>
                <div className="flex items-center gap-1 sm:gap-2 flex-wrap justify-center">
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={!canPrev}
                    onClick={() => fetchEntries(page - 1)}
                  >
                    <ChevronLeft className="w-4 h-4" />
                    Previous
                  </Button>
                  {pageNumbers.map((pageIndex) => (
                    <Button
                      key={pageIndex}
                      variant={pageIndex === page ? 'default' : 'outline'}
                      size="sm"
                      className={pageIndex === page ? 'bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]' : 'min-w-[2rem]'}
                      onClick={() => fetchEntries(pageIndex)}
                    >
                      {pageIndex + 1}
                    </Button>
                  ))}
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={!canNext}
                    onClick={() => fetchEntries(page + 1)}
                  >
                    Next
                    <ChevronRight className="w-4 h-4" />
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

    </div>
  );
}
