import { ArrowLeft, Calendar, CheckCircle2, Clock, FileText, MapPin, MessageSquare, Upload, User, XCircle } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { resignationService } from '@/services/resignation.service';
import { formatDateTime } from '@/components/ui/utils';
import { RESIGNATION_STAGE_OPTIONS, RESIGNATION_DOCUMENT_TYPES } from '@/lib/offboardingDocumentOptions';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface DealerResignationDetailsPageProps {
  resignationId: string;
  onBack: () => void;
}

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

export function DealerResignationDetailsPage({ resignationId, onBack }: DealerResignationDetailsPageProps) {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [details, setDetails] = useState<any>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadFile, setUploadFile] = useState<File | null>(null);
  const [uploadDocType, setUploadDocType] = useState<string>(RESIGNATION_DOCUMENT_TYPES[0]);
  const [uploadStage, setUploadStage] = useState<string>('');
  const [auditLogs, setAuditLogs] = useState<any[]>([]);
  const [withdrawing, setWithdrawing] = useState(false);
  const [isWithdrawDialogOpen, setIsWithdrawDialogOpen] = useState(false);
  const [withdrawalReason, setWithdrawalReason] = useState('User requested withdrawal');

  useEffect(() => {
    const fetchDetails = async () => {
      try {
        setLoading(true);
        const [data, audits] = await Promise.all([
          resignationService.getResignationById(resignationId),
          fetchAuditLogs(resignationId)
        ]);
        setDetails(data);
        setAuditLogs(audits);
      } catch (error) {
        console.error('Failed to fetch resignation details:', error);
        toast.error('Unable to load resignation details');
      } finally {
        setLoading(false);
      }
    };

    if (resignationId) {
      fetchDetails();
    }
  }, [resignationId]);

  const fetchAuditLogs = async (id: string) => {
    try {
      // Lazy import through existing API helper shape used in other modules.
      const { API } = await import('@/api/API');
      const response = await API.getAuditLogs('resignation', id) as any;
      if (response?.data?.success) return response.data.data || [];
      return [];
    } catch (error) {
      return [];
    }
  };

  const refreshDetails = async () => {
    try {
      const [data, audits] = await Promise.all([
        resignationService.getResignationById(resignationId),
        fetchAuditLogs(resignationId)
      ]);
      setDetails(data);
      setAuditLogs(audits);
    } catch (error) {
      toast.error('Unable to refresh resignation details');
    }
  };

  const handleUpload = async () => {
    if (!uploadFile) {
      toast.error('Please choose a file');
      return;
    }
    try {
      setUploading(true);
      const formData = new FormData();
      formData.append('file', uploadFile);
      formData.append('documentType', uploadDocType);
      if (uploadStage) formData.append('stage', uploadStage);
      await resignationService.uploadDocument(resignationId, formData);
      toast.success('Document uploaded successfully');
      setUploadFile(null);
      await refreshDetails();
    } catch (error: any) {
      toast.error(error?.response?.data?.message || 'Document upload failed');
    } finally {
      setUploading(false);
    }
  };

  const handleWithdraw = async () => {
    try {
      setWithdrawing(true);
      await resignationService.withdraw(resignationId, withdrawalReason);
      toast.success('Resignation request withdrawn successfully');
      setIsWithdrawDialogOpen(false);
      await refreshDetails();
    } catch (error: any) {
      toast.error(error?.response?.data?.message || 'Failed to withdraw resignation');
    } finally {
      setWithdrawing(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-[320px] flex items-center justify-center">
        <Clock className="w-8 h-8 animate-spin text-amber-600" />
      </div>
    );
  }

  if (!details) {
    return (
      <div className="space-y-4">
        <Button variant="outline" onClick={onBack}>
          <ArrowLeft className="w-4 h-4 mr-2" />
          Back
        </Button>
        <Card>
          <CardContent className="py-8 text-center text-slate-600">
            Resignation details not found.
          </CardContent>
        </Card>
      </div>
    );
  }

  const docs = details.uploadedDocuments || [];
  const timeline = Array.isArray(details.timeline) ? details.timeline : [];

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <Button variant="outline" onClick={onBack}>
          <ArrowLeft className="w-4 h-4 mr-2" />
          Back
        </Button>
        <div className="flex-1">
          <h1 className="text-slate-900">Resignation Request Details</h1>
          <p className="text-slate-600 text-sm">
            Track your request progress and uploaded documents
          </p>
        </div>
        {details.status !== 'Withdrawn' && 
         details.status !== 'Completed' && 
         details.status !== 'Rejected' && 
         !['NBH', 'DD Admin', 'Legal', 'F&F Initiated'].includes(details.currentStage) && (
          <Button 
            variant="destructive" 
            className="bg-red-600 hover:bg-red-700"
            onClick={() => setIsWithdrawDialogOpen(true)}
            disabled={withdrawing}
          >
            <XCircle className="w-4 h-4 mr-2" />
            {withdrawing ? 'Withdrawing...' : 'Withdraw Request'}
          </Button>
        )}
      </div>

      <AlertDialog open={isWithdrawDialogOpen} onOpenChange={setIsWithdrawDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action will withdraw your resignation request. This action cannot be undone and you will need to submit a new request if you change your mind.
            </AlertDialogDescription>
            <div className="mt-4 space-y-2">
              <Label htmlFor="withdrawal-reason">Reason for withdrawal</Label>
              <Input 
                id="withdrawal-reason"
                placeholder="Please enter a reason..."
                value={withdrawalReason}
                onChange={(e) => setWithdrawalReason(e.target.value)}
              />
            </div>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={withdrawing}>Cancel</AlertDialogCancel>
            <AlertDialogAction 
              onClick={(e) => {
                e.preventDefault();
                handleWithdraw();
              }}
              className="bg-red-600 hover:bg-red-700 text-white"
              disabled={withdrawing}
            >
              {withdrawing ? 'Withdrawing...' : 'Yes, Withdraw Request'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <CheckCircle2 className="w-5 h-5 text-amber-600" />
            Request Summary
          </CardTitle>
          <CardDescription>Current request status and key metadata</CardDescription>
        </CardHeader>
        <CardContent className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <p className="text-xs text-slate-500">Request ID</p>
            <p className="text-slate-900">{details.resignationId || details.id}</p>
          </div>
          <div>
            <p className="text-xs text-slate-500">Status</p>
            <Badge className={`border ${getStatusColor(details.status || 'Pending')}`}>
              {details.status || 'Pending'}
            </Badge>
          </div>
          <div>
            <p className="text-xs text-slate-500">Current Stage</p>
            <p className="text-slate-900">{details.currentStage || 'Submitted'}</p>
          </div>
          <div>
            <p className="text-xs text-slate-500">Submitted On</p>
            <p className="text-slate-900">{formatDateTime(details.submittedOn || details.createdAt)}</p>
          </div>
          <div>
            <p className="text-xs text-slate-500">Resignation Type</p>
            <p className="text-slate-900">{details.resignationType || 'N/A'}</p>
          </div>
          <div>
            <p className="text-xs text-slate-500">Progress</p>
            <p className="text-slate-900">{details.progressPercentage || 0}%</p>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <User className="w-5 h-5 text-blue-600" />
            Outlet and Dates
          </CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <p className="text-xs text-slate-500">Outlet</p>
            <p className="text-slate-900">{details.outlet?.name || 'N/A'}</p>
          </div>
          <div>
            <p className="text-xs text-slate-500">Outlet Code</p>
            <p className="text-slate-900">{details.outlet?.code || 'N/A'}</p>
          </div>
          <div>
            <p className="text-xs text-slate-500">Last Operational Date (Sales)</p>
            <p className="text-slate-900">{details.lastOperationalDateSales ? formatDateTime(details.lastOperationalDateSales) : 'N/A'}</p>
          </div>
          <div>
            <p className="text-xs text-slate-500">Last Operational Date (Services)</p>
            <p className="text-slate-900">{details.lastOperationalDateServices ? formatDateTime(details.lastOperationalDateServices) : 'N/A'}</p>
          </div>
          <div className="md:col-span-2">
            <p className="text-xs text-slate-500">Reason</p>
            <p className="text-slate-900">{details.reason || '-'}</p>
          </div>
          <div className="md:col-span-2">
            <p className="text-xs text-slate-500 flex items-center gap-1">
              <MapPin className="w-3 h-3" />
              Outlet Address
            </p>
            <p className="text-slate-900">{details.outlet?.address || '-'}</p>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="w-5 h-5 text-purple-600" />
            Uploaded Documents
          </CardTitle>
          <CardDescription>Dealer can upload resignation-related documents for review</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-3 mb-4 p-3 border rounded-lg bg-slate-50">
            <div>
              <Label className="text-xs">Document Type</Label>
              <Select value={uploadDocType} onValueChange={setUploadDocType}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {RESIGNATION_DOCUMENT_TYPES.map((docType) => (
                    <SelectItem key={docType} value={docType}>{docType}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="text-xs">Stage (Optional)</Label>
              <Select value={uploadStage || 'none'} onValueChange={(v) => setUploadStage(v === 'none' ? '' : v)}>
                <SelectTrigger>
                  <SelectValue placeholder="Select stage" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">No Stage</SelectItem>
                  {RESIGNATION_STAGE_OPTIONS.map((stage) => (
                    <SelectItem key={stage} value={stage}>{stage}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="text-xs">File</Label>
              <input
                type="file"
                className="h-10 w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm"
                onChange={(e) => setUploadFile(e.target.files?.[0] || null)}
              />
            </div>
            <div className="flex items-end">
              <Button className="w-full" onClick={handleUpload} disabled={uploading}>
                <Upload className="w-4 h-4 mr-2" />
                {uploading ? 'Uploading...' : 'Upload'}
              </Button>
            </div>
          </div>

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Document Type</TableHead>
                <TableHead>File</TableHead>
                <TableHead>Uploaded By</TableHead>
                <TableHead>Uploaded On</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {docs.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={4} className="text-center text-slate-500 py-6">
                    No documents uploaded yet.
                  </TableCell>
                </TableRow>
              ) : (
                docs.map((doc: any) => (
                  <TableRow key={doc.id}>
                    <TableCell>{doc.documentType || '-'}</TableCell>
                    <TableCell>{doc.fileName || '-'}</TableCell>
                    <TableCell>{doc.uploader?.fullName || '-'}</TableCell>
                    <TableCell>{formatDateTime(doc.createdAt)}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <MessageSquare className="w-5 h-5 text-blue-600" />
            Work Notes Communication
          </CardTitle>
          <CardDescription>Official channel for internal-dealer clarifications</CardDescription>
        </CardHeader>
        <CardContent>
          <Button
            variant="outline"
            onClick={() =>
              navigate(`/worknotes/resignation/${resignationId}`, {
                state: {
                  applicationName: details?.dealer?.fullName || 'Resignation Request',
                  registrationNumber: details?.resignationId || resignationId
                }
              })
            }
          >
            <MessageSquare className="w-4 h-4 mr-2" />
            Open Work Notes
          </Button>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calendar className="w-5 h-5 text-amber-600" />
            Progress Timeline
          </CardTitle>
        </CardHeader>
        <CardContent>
          {timeline.length === 0 ? (
            <p className="text-sm text-slate-500">No timeline events available yet.</p>
          ) : (
            <div className="space-y-2">
              {timeline.slice().reverse().map((entry: any, idx: number) => (
                <div key={`${entry.timestamp || entry.createdAt}-${idx}`} className="p-3 border rounded-lg bg-slate-50">
                  <p className="text-sm text-slate-900">{entry.action || entry.stage || 'Stage Update'}</p>
                  <p className="text-xs text-slate-500">{formatDateTime(entry.timestamp || entry.createdAt)}</p>
                  <p className="text-xs text-slate-600">{entry.comments || entry.remarks || 'No remarks'}</p>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Audit Trail</CardTitle>
          <CardDescription>Traceability of status/actions on this request</CardDescription>
        </CardHeader>
        <CardContent>
          {auditLogs.length === 0 ? (
            <p className="text-sm text-slate-500">No audit records found.</p>
          ) : (
            <div className="space-y-2">
              {auditLogs.map((log: any) => (
                <div key={log.id} className="p-3 border rounded-lg">
                  <div className="flex items-center justify-between">
                    <p className="text-sm text-slate-900">{log.action || 'Action'}</p>
                    <p className="text-xs text-slate-500">{formatDateTime(log.createdAt || log.timestamp)}</p>
                  </div>
                  <p className="text-xs text-slate-600 mt-1">{log.remarks || log.description || 'No remarks'}</p>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
