import { ArrowLeft, CheckCircle2, Clock, MapPin, User, XCircle } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { resignationService } from '@/services/resignation.service';
import { formatDateTime } from '@/components/ui/utils';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

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

export function DealerResignationDetailsPage({ resignationId, onBack }: DealerResignationDetailsPageProps) {
  const [loading, setLoading] = useState(true);
  const [details, setDetails] = useState<any>(null);
  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 = await resignationService.getResignationById(resignationId);
        setDetails(data);
      } 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 refreshDetails = async () => {
    try {
      const data = await resignationService.getResignationById(resignationId);
      setDetails(data);
    } catch (error) {
      toast.error('Unable to refresh resignation details');
    }
  };

  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-re-red" />
      </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>
    );
  }

  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">
            Review your resignation request details
          </p>
        </div>
        {details.status !== 'Withdrawn' && 
         details.status !== 'Completed' && 
         details.status !== 'Rejected' && 
         !['NBH', 'DD Admin', 'Legal', 'Awaiting F&F', '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-re-red" />
            Request Summary
          </CardTitle>
          <CardDescription>Key details about your resignation request</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">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>
        </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>
    </div>
  );
}
