import { FileText, Calendar, Building, Plus, Eye, ArrowRight, Shield, Loader2 } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useState, useEffect } from 'react';
import { User as UserType } from '@/lib/mock-data';
import { toast } from 'sonner';
import { API } from '@/api/API';
import { formatDateTime } from '@/components/ui/utils';
import { normalizeDealerProfileConstitution } from '@/lib/constitutional-change';
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";

interface ConstitutionalChangePageProps {
  currentUser?: UserType | null;
  onViewDetails: (id: string) => void;
}

// Document requirements mapping (keys = DB `changeType` ENUM values)
const documentRequirements: Record<string, number[]> = {
  'Partnership': [1, 2, 3, 4, 8, 9, 10, 16],
  'LLP': [1, 2, 3, 7, 8, 10, 11, 16],
  'Private Limited': [1, 2, 3, 5, 6, 7, 8, 10, 16],
  'Proprietorship': [1, 2, 3, 10, 16]
};

// Document names
const OTHER_DOCUMENT_DOC_NUMBER = 99;

const documentNames: Record<number, string> = {
  1: 'GST',
  2: 'Firm Pan Copy',
  3: 'Self attested KYC\'s',
  4: 'Partnership Agreement (Notarised)',
  5: 'MOA (Applicable for Only Pvt.Ltd)',
  6: 'AOA (Applicable for Only Pvt.Ltd)',
  7: 'COI (Applicable for Only Pvt.Ltd & LLP)',
  8: 'BPA - Business Purchase Agreement',
  9: 'Firm Registration Certificate (Partnership)',
  10: 'Cancelled Cheque',
  11: 'LLP Agreement (Notarised)',
  12: 'ZBH Approval',
  13: 'NBH Approval',
  14: 'RBM Approval',
  15: 'DD-Lead Approval',
  16: 'Declaration / Authorization Letter',
  [OTHER_DOCUMENT_DOC_NUMBER]: 'Other'
};

const getStatusColor = (status: string) => {
  if (status === 'Completed') return 'bg-green-100 text-green-700 border-green-300';
  if (status.includes('Review') || status.includes('Pending')) return 'bg-yellow-100 text-yellow-700 border-yellow-300';
  if (status.includes('Rejected')) return 'bg-red-100 text-red-700 border-red-300';
  if (status.includes('Collection')) return 'bg-blue-100 text-blue-700 border-blue-300';
  return 'bg-slate-100 text-slate-700 border-slate-300';
};

const getTypeColor = (type: string) => {
  switch(type) {
    case 'Proprietorship': return 'bg-purple-100 text-purple-700 border-purple-300';
    case 'Partnership': return 'bg-blue-100 text-blue-700 border-blue-300';
    case 'LLP':
      return 'bg-indigo-100 text-indigo-700 border-indigo-300';
    case 'Private Limited':
      return 'bg-cyan-100 text-cyan-700 border-cyan-300';
    default: return 'bg-slate-100 text-slate-700 border-slate-300';
  }
};

export function ConstitutionalChangePage({ onViewDetails }: ConstitutionalChangePageProps) {
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [structureTargets, setStructureTargets] = useState<{ value: string; label: string }[]>([]);
  const [dealers, setDealers] = useState<any[]>([]);
  const [allOutlets, setAllOutlets] = useState<any[]>([]);
  const [selectedDealerUserId, setSelectedDealerUserId] = useState('');
  const [selectedOutletId, setSelectedOutletId] = useState('');
  const [outletsForDealer, setOutletsForDealer] = useState<any[]>([]);
  const [dealerData, setDealerData] = useState<any>(null);
  const [targetType, setTargetType] = useState('');
  const [reason, setReason] = useState('');
  const [requiredDocs, setRequiredDocs] = useState<number[]>([]);
  const [requests, setRequests] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [paginationMeta, setPaginationMeta] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('all');
  const itemsPerPage = 10;
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [dialogDataLoading, setDialogDataLoading] = useState(false);

  const isCompletedRequest = (request: any) =>
    request.status === 'Completed' || request.status === 'Closed' || request.currentStage === 'Completed';

  const isRejectedRequest = (request: any) =>
    request.status === 'Rejected' || request.status === 'Revoked' || request.currentStage === 'Rejected' || request.currentStage === 'Revoked';

  const isPendingReviewRequest = (request: any) =>
    !isCompletedRequest(request) && !isRejectedRequest(request) && request.status !== 'Submitted';

  const isSubmittedRequest = (request: any) =>
    request.status === 'Submitted' || request.currentStage === 'Submitted';

  const handleTabChange = (val: string) => {
    setActiveTab(val);
    setCurrentPage(1);
  };

  useEffect(() => {
    fetchRequests();
  }, [currentPage, activeTab]);

  useEffect(() => {
    if (!isDialogOpen) return;
    let cancelled = false;
    (async () => {
      try {
        setDialogDataLoading(true);
        const [metaRes, dealersRes, outletsRes] = await Promise.all([
          API.getConstitutionalChangeMeta() as any,
          API.getDealers({ onboarded: 'true' }) as any,
          API.getOutlets() as any
        ]);
        if (cancelled) return;
        if (metaRes.data?.success && Array.isArray(metaRes.data.structureTargets)) {
          setStructureTargets(metaRes.data.structureTargets);
        }
        const dealerRows = dealersRes.data?.data ?? dealersRes.data?.dealers ?? [];
        setDealers(Array.isArray(dealerRows) ? dealerRows : []);
        const outlets = outletsRes.data?.outlets ?? [];
        setAllOutlets(Array.isArray(outlets) ? outlets : []);
      } catch (e) {
        console.error(e);
        toast.error('Failed to load dealers or form options');
      } finally {
        if (!cancelled) setDialogDataLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [isDialogOpen]);

  const fetchRequests = async () => {
    try {
      setIsLoading(true);
      const response = await API.getConstitutionalChanges({
        page: currentPage,
        limit: itemsPerPage,
        status: activeTab === 'all' ? undefined : activeTab
      }) as any;
      if (response.data.success) {
        setRequests(response.data.requests || []);
        setPaginationMeta(response.meta);
      }
    } catch (error: any) {
      console.error('Fetch requests error:', error);
      toast.error('Failed to fetch requests');
    } finally {
      setIsLoading(false);
    }
  };

  const handleDealerUserSelect = (dealerUserId: string) => {
    setSelectedDealerUserId(dealerUserId);
    setSelectedOutletId('');
    setTargetType('');
    setRequiredDocs([]);
    if (!dealerUserId) {
      setDealerData(null);
      setOutletsForDealer([]);
      return;
    }
    const row = dealers.find((d: any) => d.user?.id === dealerUserId);
    if (!row?.user?.id) {
      setDealerData(null);
      setOutletsForDealer([]);
      return;
    }
    const norm = normalizeDealerProfileConstitution(row.constitutionType);
    const outs = allOutlets.filter((o: any) => String(o.dealerId) === String(dealerUserId));
    setOutletsForDealer(outs);
    if (outs.length === 1) {
      setSelectedOutletId(outs[0].id);
    }
    setDealerData({
      dealerUserId: row.user.id,
      dealerName: row.businessName,
      dealershipName: row.legalName || row.businessName,
      address: row.registeredAddress || row.application?.preferredLocation || '—',
      gst: row.gstNumber || 'N/A',
      currentType: norm,
      dealerCode: row.dealerCode?.dealerCode || '—',
      region: '—',
      zone: '—'
    });
  };

  const handleTargetTypeChange = (type: string) => {
    setTargetType(type);
    setRequiredDocs(documentRequirements[type] || []);
  };

  const handleSubmitRequest = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!dealerData?.dealerUserId) {
      toast.error('Please select a dealer');
      return;
    }

    if (outletsForDealer.length > 1 && !selectedOutletId) {
      toast.error('Please select an outlet for this dealer');
      return;
    }

    if (!targetType) {
      toast.error('Please select proposed constitution type');
      return;
    }

    if (!reason.trim()) {
      toast.error('Please provide a reason for constitutional change');
      return;
    }

    if (dealerData.currentType === targetType) {
      toast.error('Proposed type cannot be the same as the current constitution');
      return;
    }

    try {
      setIsSubmitting(true);
      const payload = {
        forDealerUserId: dealerData.dealerUserId,
        outletId: selectedOutletId || undefined,
        changeType: targetType,
        reason: reason.trim(),
        currentConstitution: dealerData.currentType
      };
      
      const response = await API.createConstitutionalChange(payload) as any;
      if (response.data.success) {
        toast.success('Constitutional change request submitted successfully');
        setIsDialogOpen(false);
        fetchRequests();
        
        // Reset form
        setSelectedDealerUserId('');
        setSelectedOutletId('');
        setOutletsForDealer([]);
        setDealerData(null);
        setTargetType('');
        setReason('');
        setRequiredDocs([]);
      }
    } catch (error: any) {
      console.error('Submit request error:', error);
      const msg = error?.response?.data?.message || 'Failed to submit request';
      toast.error(msg);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Statistics
  const stats = [
    {
      title: 'Total Requests',
      value: paginationMeta?.stats?.total || 0,
      icon: FileText,
      color: 'bg-blue-500',
    },
    {
      title: 'Submitted / Review',
      value: paginationMeta?.stats?.pending || 0,
      icon: Calendar,
      color: 'bg-yellow-500',
    },
    {
      title: 'Completed',
      value: paginationMeta?.stats?.completed || 0,
      icon: Shield,
      color: 'bg-green-500',
    },
    {
      title: 'Rejected / Revoked',
      value: paginationMeta?.stats?.rejected || 0,
      icon: Building,
      color: 'bg-red-500',
    },
  ];

  return (
    <div className="space-y-6">
      {/* Loading Overlay */}
      {isLoading && (
        <div className="fixed inset-0 bg-slate-900/20 backdrop-blur-sm z-50 flex items-center justify-center">
          <Loader2 className="w-8 h-8 text-amber-600 animate-spin" />
        </div>
      )}

      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-slate-900 mb-2">Constitutional Change Management</h1>
          <p className="text-slate-600">
            Manage dealership constitutional change requests - Adding/Removing partners or changing business structure
          </p>
        </div>
        
        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogTrigger asChild>
            <Button className="bg-amber-600 hover:bg-amber-700">
              <Plus className="w-4 h-4 mr-2" />
              New Request
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create Constitutional Change Request</DialogTitle>
              <DialogDescription>
                Submit a request for dealership constitutional change. All fields are mandatory.
              </DialogDescription>
            </DialogHeader>
            
            <form onSubmit={handleSubmitRequest} className="space-y-4">
              {dialogDataLoading && (
                <div className="flex items-center gap-2 text-sm text-slate-500 py-2">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Loading dealers and options…
                </div>
              )}

              {/* Dealer (onboarded) — same POST as dealer self-service, with forDealerUserId */}
              <div className="space-y-2">
                <Label htmlFor="dealerUser">Dealer *</Label>
                <Select
                  value={selectedDealerUserId}
                  onValueChange={handleDealerUserSelect}
                  disabled={dialogDataLoading}
                  required
                >
                  <SelectTrigger id="dealerUser">
                    <SelectValue placeholder="Select dealer account" />
                  </SelectTrigger>
                  <SelectContent className="max-h-72">
                    {dealers
                      .filter((d: any) => d.user?.id)
                      .map((d: any) => (
                        <SelectItem key={d.user.id} value={d.user.id}>
                          {(d.dealerCode?.dealerCode || 'No code') + ' — ' + (d.businessName || d.legalName || 'Dealer')}
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                <p className="text-xs text-slate-500">
                  Internal users create the request on behalf of the selected dealer; the workflow uses the same endpoint as dealer-initiated requests.
                </p>
              </div>

              {outletsForDealer.length > 1 && (
                <div className="space-y-2">
                  <Label htmlFor="outletPick">Outlet *</Label>
                  <Select value={selectedOutletId} onValueChange={setSelectedOutletId} required>
                    <SelectTrigger id="outletPick">
                      <SelectValue placeholder="Select outlet" />
                    </SelectTrigger>
                    <SelectContent>
                      {outletsForDealer.map((o: any) => (
                        <SelectItem key={o.id} value={o.id}>
                          {o.code} — {o.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}

              {/* Auto-populated Dealer Details */}
              {dealerData && (
                <div className="bg-slate-50 border border-slate-200 rounded-lg p-4 space-y-3">
                  <h3 className="text-slate-900">Dealer Details</h3>
                  <div className="grid grid-cols-2 gap-3 text-sm">
                    <div>
                      <span className="text-slate-600">Dealer Code:</span>
                      <p className="text-slate-900">{dealerData.dealerCode}</p>
                    </div>
                    <div>
                      <span className="text-slate-600">Dealer Name:</span>
                      <p className="text-slate-900">{dealerData.dealerName}</p>
                    </div>
                    <div>
                      <span className="text-slate-600">Legal / display name:</span>
                      <p className="text-slate-900">{dealerData.dealershipName}</p>
                    </div>
                    <div>
                      <span className="text-slate-600">Address:</span>
                      <p className="text-slate-900">{dealerData.address}</p>
                    </div>
                    <div>
                      <span className="text-slate-600">GST:</span>
                      <p className="text-slate-900">{dealerData.gst}</p>
                    </div>
                    <div>
                      <span className="text-slate-600">Current constitution (from profile):</span>
                      <Badge className={getTypeColor(dealerData.currentType)}>
                        {dealerData.currentType}
                      </Badge>
                    </div>
                  </div>
                </div>
              )}

              {/* Proposed constitution — ENUM-aligned options from API */}
              <div className="space-y-2">
                <Label htmlFor="targetType">Proposed constitution *</Label>
                <Select value={targetType} onValueChange={handleTargetTypeChange} required>
                  <SelectTrigger>
                    <SelectValue placeholder="Select proposed constitution" />
                  </SelectTrigger>
                  <SelectContent>
                    {structureTargets
                      .filter((opt) => opt.value !== dealerData?.currentType)
                      .map((opt) => (
                        <SelectItem key={opt.value} value={opt.value}>
                          {opt.label}
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                {dealerData && targetType && dealerData.currentType === targetType && (
                  <p className="text-red-600 text-sm">Target type cannot be same as current type</p>
                )}
              </div>

              {/* Required Documents Display */}
              {targetType && requiredDocs.length > 0 && (
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 space-y-2">
                  <h4 className="text-blue-900">Required Documents for {targetType}</h4>
                  <div className="grid grid-cols-1 gap-2">
                    {requiredDocs.map((docNum) => (
                      <div key={docNum} className="flex items-start gap-2 text-sm">
                        <span className="text-blue-600 font-medium">{docNum}.</span>
                        <span className="text-blue-800">{documentNames[docNum]}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Reason */}
              <div className="space-y-2">
                <Label htmlFor="reason">Reason for Constitutional Change *</Label>
                <Textarea
                  id="reason"
                  placeholder="Provide detailed reason for the constitutional change request..."
                  value={reason}
                  onChange={(e) => setReason(e.target.value)}
                  rows={4}
                  required
                />
              </div>

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsDialogOpen(false)}
                >
                  Cancel
                </Button>
                <Button 
                  type="submit"
                  className="bg-amber-600 hover:bg-amber-700"
                  disabled={
                    !dealerData ||
                    !targetType ||
                    (dealerData && dealerData.currentType === targetType) ||
                    (outletsForDealer.length > 1 && !selectedOutletId) ||
                    dialogDataLoading ||
                    isSubmitting
                  }
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Submitting...
                    </>
                  ) : (
                    'Submit Request'
                  )}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat, index) => {
          const Icon = stat.icon;
          return (
            <Card key={index}>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-slate-600 text-sm">{stat.title}</p>
                    <p className="text-slate-900 text-2xl mt-1">{stat.value}</p>
                  </div>
                  <div className={`${stat.color} w-12 h-12 rounded-lg flex items-center justify-center`}>
                    <Icon className="w-6 h-6 text-white" />
                  </div>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Requests Table */}
      <Card>
        <CardHeader>
          <CardTitle>Constitutional Change Requests</CardTitle>
          <CardDescription>
            Track and manage all constitutional change requests across all stages
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Tabs value={activeTab} onValueChange={handleTabChange} className="w-full">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="all">All Requests</TabsTrigger>
              <TabsTrigger value="pending">Submitted / Review</TabsTrigger>
              <TabsTrigger value="rejected">Rejected / Revoked</TabsTrigger>
              <TabsTrigger value="completed">Completed</TabsTrigger>
            </TabsList>

            <TabsContent value="all" className="mt-4">
              <div className="border border-slate-200 rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-slate-50">
                      <TableHead>Request ID</TableHead>
                      <TableHead>Dealer Details</TableHead>
                      <TableHead>Constitutional Change</TableHead>
                      <TableHead>Current Stage</TableHead>
                      <TableHead>Progress</TableHead>
                      <TableHead>Submitted On</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {requests.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} className="text-center py-8 text-slate-500">
                          No constitutional change requests found
                        </TableCell>
                      </TableRow>
                    ) : (
                      requests.map((request: any) => (
                        <TableRow key={request.requestId}>
                          <TableCell>
                            <div className="font-medium text-slate-900">{request.requestId}</div>
                            <div className="text-slate-600 text-sm">{request.dealer?.dealerProfile?.dealerCode?.dealerCode || request.outlet?.code || 'N/A'}</div>
                          </TableCell>
                          <TableCell>
                            <div className="font-medium text-slate-900">{request.dealer?.dealerProfile?.businessName || request.outlet?.name || 'N/A'}</div>
                            <div className="text-slate-600 text-sm">
                              {request.dealer?.dealerProfile?.registeredAddress || 
                               (request.outlet?.city && request.outlet?.state ? `${request.outlet.city}, ${request.outlet.state}` : 
                               (request.dealer?.dealerProfile?.application?.city || request.outlet?.address || 'N/A'))}
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <Badge className={getTypeColor(request.currentConstitution || 'Proprietorship')}>
                                {request.currentConstitution || '—'}
                              </Badge>
                              <ArrowRight className="w-4 h-4 text-slate-400" />
                              <Badge className={getTypeColor(request.changeType)}>
                                {request.changeType}
                              </Badge>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge variant="outline" className="border-slate-300 text-slate-700">
                              {request.currentStage}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <div className="flex-1 h-2 bg-slate-200 rounded-full overflow-hidden">
                                <div 
                                  className="h-full bg-amber-600 transition-all duration-300"
                                  style={{ width: `${request.progressPercentage || 0}%` }}
                                />
                              </div>
                              <span className="text-slate-600 text-sm">{request.progressPercentage || 0}%</span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="text-slate-900">{formatDateTime(request.createdAt)}</div>
                            <div className="text-slate-600 text-sm">By {request.dealer?.fullName || 'Dealer'}</div>
                          </TableCell>
                          <TableCell>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => onViewDetails(request.requestId)}
                            >
                              <Eye className="w-4 h-4 mr-1" />
                              View
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </TabsContent>

            <TabsContent value="pending" className="mt-4">
              <div className="border border-slate-200 rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-slate-50">
                      <TableHead>Request ID</TableHead>
                      <TableHead>Dealer Details</TableHead>
                      <TableHead>Constitutional Change</TableHead>
                      <TableHead>Current Stage</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {requests
                      .filter((r: any) => isSubmittedRequest(r) || isPendingReviewRequest(r))
                      .map((request: any) => (
                        <TableRow key={request.requestId}>
                          <TableCell>
                            <div className="font-medium text-slate-900">{request.requestId}</div>
                            <div className="text-slate-600 text-sm">{request.dealer?.dealerProfile?.dealerCode?.dealerCode || request.outlet?.code || 'N/A'}</div>
                          </TableCell>
                          <TableCell>
                            <div className="font-medium text-slate-900">{request.dealer?.dealerProfile?.businessName || request.outlet?.name || 'N/A'}</div>
                            <div className="text-slate-600 text-sm">
                              {request.dealer?.dealerProfile?.registeredAddress || 
                               (request.outlet?.city && request.outlet?.state ? `${request.outlet.city}, ${request.outlet.state}` : (request.outlet?.address || 'N/A'))}
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <Badge className={getTypeColor(request.currentConstitution || 'Proprietorship')}>
                                {request.currentConstitution || '—'}
                              </Badge>
                              <ArrowRight className="w-4 h-4 text-slate-400" />
                              <Badge className={getTypeColor(request.changeType)}>
                                {request.changeType}
                              </Badge>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge variant="outline" className="border-slate-300 text-slate-700">
                              {request.currentStage}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Badge className={getStatusColor(request.status)}>
                              {request.status}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => onViewDetails(request.requestId)}
                            >
                              <Eye className="w-4 h-4 mr-1" />
                              View
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    {requests.filter((r: any) => isSubmittedRequest(r) || isPendingReviewRequest(r)).length === 0 && (
                      <TableRow>
                        <TableCell colSpan={6} className="text-center py-8 text-slate-500">
                          No pending requests found
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </TabsContent>

            <TabsContent value="in-progress" className="mt-4">
              <div className="border border-slate-200 rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-slate-50">
                      <TableHead>Request ID</TableHead>
                      <TableHead>Dealer Details</TableHead>
                      <TableHead>Constitutional Change</TableHead>
                      <TableHead>Progress</TableHead>
                      <TableHead>Current Stage</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {requests
                      .filter((r: any) => isRejectedRequest(r))
                      .map((request: any) => (
                        <TableRow key={request.requestId}>
                          <TableCell>
                            <div className="font-medium text-slate-900">{request.requestId}</div>
                            <div className="text-slate-600 text-sm">{request.dealer?.dealerProfile?.dealerCode?.dealerCode || request.outlet?.code || 'N/A'}</div>
                          </TableCell>
                          <TableCell>
                            <div className="font-medium text-slate-900">{request.dealer?.dealerProfile?.businessName || request.outlet?.name || 'N/A'}</div>
                            <div className="text-slate-600 text-sm">
                              {request.dealer?.dealerProfile?.registeredAddress || 
                               (request.outlet?.city && request.outlet?.state ? `${request.outlet.city}, ${request.outlet.state}` : 
                               (request.dealer?.dealerProfile?.application?.city || request.outlet?.address || 'N/A'))}
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <Badge className={getTypeColor(request.currentConstitution || 'Proprietorship')}>
                                {request.currentConstitution || '—'}
                              </Badge>
                              <ArrowRight className="w-4 h-4 text-slate-400" />
                              <Badge className={getTypeColor(request.changeType)}>
                                {request.changeType}
                              </Badge>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <div className="flex-1 h-2 bg-slate-200 rounded-full overflow-hidden">
                                <div 
                                  className="h-full bg-amber-600 transition-all duration-300"
                                  style={{ width: `${request.progressPercentage || 0}%` }}
                                />
                              </div>
                              <span className="text-slate-600 text-sm">{request.progressPercentage || 0}%</span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge variant="outline" className="border-slate-300 text-slate-700">
                              {request.currentStage}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => onViewDetails(request.requestId)}
                            >
                              <Eye className="w-4 h-4 mr-1" />
                              View
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    {requests.filter((r: any) => isRejectedRequest(r)).length === 0 && (
                      <TableRow>
                        <TableCell colSpan={6} className="text-center py-8 text-slate-500">
                          No in-progress requests found
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </TabsContent>

            <TabsContent value="completed" className="mt-4">
              <div className="border border-slate-200 rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-slate-50">
                      <TableHead>Request ID</TableHead>
                      <TableHead>Dealer Details</TableHead>
                      <TableHead>Constitutional Change</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Submitted On</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {requests
                      .filter((r: any) => isCompletedRequest(r))
                      .map((request: any) => (
                        <TableRow key={request.requestId}>
                          <TableCell>
                            <div className="font-medium text-slate-900">{request.requestId}</div>
                            <div className="text-slate-600 text-sm">{request.dealer?.dealerProfile?.dealerCode?.dealerCode || request.outlet?.code || 'N/A'}</div>
                          </TableCell>
                          <TableCell>
                            <div className="font-medium text-slate-900">{request.dealer?.dealerProfile?.businessName || request.outlet?.name || 'N/A'}</div>
                            <div className="text-slate-600 text-sm">
                              {request.dealer?.dealerProfile?.registeredAddress || 
                               (request.outlet?.city && request.outlet?.state ? `${request.outlet.city}, ${request.outlet.state}` : (request.outlet?.address || 'N/A'))}
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <Badge className={getTypeColor(request.currentConstitution || 'Proprietorship')}>
                                {request.currentConstitution || '—'}
                              </Badge>
                              <ArrowRight className="w-4 h-4 text-slate-400" />
                              <Badge className={getTypeColor(request.changeType)}>
                                {request.changeType}
                              </Badge>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge className={getStatusColor(request.status)}>
                              {request.status}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <div className="text-slate-900">{formatDateTime(request.createdAt)}</div>
                          </TableCell>
                          <TableCell>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => onViewDetails(request.requestId)}
                            >
                              <Eye className="w-4 h-4 mr-1" />
                              View
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    {requests.filter((r: any) => isCompletedRequest(r)).length === 0 && (
                      <TableRow>
                        <TableCell colSpan={6} className="text-center py-8 text-slate-500">
                          No completed requests found
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </TabsContent>
          </Tabs>

          {paginationMeta && paginationMeta.totalPages > 1 && (
            <div className="py-4 border-t flex justify-center bg-white rounded-b-lg">
              <Pagination>
                <PaginationContent>
                  <PaginationItem>
                    <PaginationPrevious 
                      onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                      className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
                    />
                  </PaginationItem>
                  
                  {[...Array(paginationMeta.totalPages)].map((_, i) => {
                    const pageNum = i + 1;
                    if (
                      pageNum === 1 || 
                      pageNum === paginationMeta.totalPages || 
                      (pageNum >= currentPage - 1 && pageNum <= currentPage + 1)
                    ) {
                      return (
                        <PaginationItem key={pageNum}>
                          <PaginationLink 
                            isActive={currentPage === pageNum}
                            onClick={() => setCurrentPage(pageNum)}
                            className="cursor-pointer"
                          >
                            {pageNum}
                          </PaginationLink>
                        </PaginationItem>
                      );
                    }
                    if (
                      (pageNum === 2 && currentPage > 3) || 
                      (pageNum === paginationMeta.totalPages - 1 && currentPage < paginationMeta.totalPages - 2)
                    ) {
                      return <PaginationItem key={pageNum}><PaginationEllipsis /></PaginationItem>;
                    }
                    return null;
                  })}

                  <PaginationItem>
                    <PaginationNext 
                      onClick={() => setCurrentPage(prev => Math.min(paginationMeta.totalPages, prev + 1))}
                      className={currentPage === paginationMeta.totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
                    />
                  </PaginationItem>
                </PaginationContent>
              </Pagination>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
