import React, { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from '@/components/ui/badge';
import { Calendar, Clock, User, FileText, CheckCircle, XCircle, AlertTriangle, Loader2 } from 'lucide-react';
import { format, parseISO } from 'date-fns';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from "@/hooks/use-toast";
import { useAuth } from '@/contexts/AuthContext';

export default function DateRequestDetailsDialog({ open, onOpenChange, request, onRefresh }) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [rejectReason, setRejectReason] = useState('');
  const [showRejectInput, setShowRejectInput] = useState(false);

  if (!request) return null;

  const handleApprove = async () => {
    setLoading(true);
    try {
      const timeStr = request.requested_time || '09:00:00';
      const startDateTime = new Date(`${request.requested_date}T${timeStr}`);
      const endDateTime = new Date(startDateTime.getTime() + 60 * 60 * 1000);

      const { error: eventError } = await supabase
        .from('calendar_events')
        .insert({
            title: `Client Request: ${request.associations?.name || 'Unknown'}`,
            description: `Auto-generated from Date Request.\n\nClient Note: ${request.task_description}\n\nAdditional Notes: ${request.notes || 'None'}`,
            start_date: startDateTime.toISOString(),
            end_date: endDateTime.toISOString(),
            association_id: request.association_id,
            event_type: 'meeting',
            created_by: user.id,
        });

      if (eventError) throw eventError;

      const { error: reqError } = await supabase
        .from('client_requests')
        .update({
            status: 'approved',
            assigned_to: user.id,
        })
        .eq('id', request.id);

      if (reqError) throw reqError;

      toast({
        title: "Request Approved",
        description: "The request has been approved and a calendar event created.",
      });
      
      onRefresh?.();
      onOpenChange(false);

    } catch (error) {
      console.error('Approval Error:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to approve request. " + error.message,
      });
    } finally {
      setLoading(false);
    }
  };

  const handleReject = async () => {
    if (!rejectReason.trim()) {
        toast({
            variant: "destructive",
            title: "Reason Required",
            description: "Please provide a reason for rejection.",
        });
        return;
    }

    setLoading(true);
    try {
      const { error } = await supabase
        .from('client_requests')
        .update({
            status: 'rejected',
            assigned_to: user.id,
            description: rejectReason
        })
        .eq('id', request.id);

      if (error) throw error;

      toast({
        title: "Request Rejected",
        description: "The request has been rejected.",
      });
      
      onRefresh?.();
      onOpenChange(false);
      setShowRejectInput(false);
      setRejectReason('');

    } catch (error) {
      console.error('Rejection Error:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to reject request. " + error.message,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-xl">
             Request Details
             <Badge className={
                request.status === 'approved' ? 'bg-green-100 text-green-800' :
                request.status === 'rejected' ? 'bg-red-100 text-red-800' :
                'bg-yellow-100 text-yellow-800'
             }>
                {request.status?.toUpperCase()}
             </Badge>
          </DialogTitle>
          <DialogDescription>
             Review the details submitted by the client.
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-6 py-4">
           <div className="flex items-start gap-4 p-4 bg-muted rounded-lg border">
               <div className="bg-background p-2 rounded-full border shadow-sm">
                   <User className="w-5 h-5 text-muted-foreground" />
               </div>
               <div>
                   <h4 className="font-semibold">{request.associations?.name || request.requester_name}</h4>
                   <p className="text-xs text-muted-foreground mt-1">Request ID: {request.id?.slice(0, 8)}</p>
               </div>
           </div>

           <div className="grid grid-cols-2 gap-4">
               <div className="space-y-1">
                   <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1">
                      <Calendar className="w-3 h-3" /> Requested Date
                   </span>
                   <p className="font-medium text-lg">
                       {request.created_at ? format(parseISO(request.created_at), 'MMMM d, yyyy') : 'N/A'}
                   </p>
               </div>
               <div className="space-y-1">
                   <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1">
                      <Clock className="w-3 h-3" /> Priority
                   </span>
                   <p className="font-medium text-lg capitalize">
                       {request.priority || 'Medium'}
                   </p>
               </div>
           </div>

           <div className="space-y-4">
               <div>
                   <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide block mb-1">
                       Title
                   </span>
                   <p className="text-sm capitalize bg-muted inline-block px-2 py-1 rounded border">
                       {request.title || 'General'}
                   </p>
               </div>

               {request.description && (
                   <div>
                       <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide block mb-1">
                           Description
                       </span>
                       <p className="text-sm leading-relaxed bg-muted p-3 rounded-md border">
                           {request.description}
                       </p>
                   </div>
               )}
           </div>

           {request.status === 'pending' || request.status === 'open' ? (
               <div className="border-t pt-4 mt-2">
                   {!showRejectInput ? (
                       <div className="flex gap-3 justify-end">
                           <Button 
                                variant="destructive" 
                                onClick={() => setShowRejectInput(true)}
                                disabled={loading}
                           >
                               <XCircle className="w-4 h-4 mr-2" /> Reject Request
                           </Button>
                           <Button 
                                onClick={handleApprove}
                                disabled={loading}
                           >
                               {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <CheckCircle className="w-4 h-4 mr-2" />}
                               Approve & Schedule
                           </Button>
                       </div>
                   ) : (
                       <div className="space-y-3 bg-destructive/10 p-4 rounded-lg border border-destructive/20">
                           <div className="flex items-center gap-2 text-destructive font-semibold mb-2">
                               <AlertTriangle className="w-4 h-4" /> Reject Request
                           </div>
                           <Textarea 
                               placeholder="Please provide a reason for rejection..." 
                               value={rejectReason}
                               onChange={(e) => setRejectReason(e.target.value)}
                           />
                           <div className="flex gap-2 justify-end">
                               <Button variant="ghost" onClick={() => setShowRejectInput(false)} disabled={loading}>
                                   Cancel
                               </Button>
                               <Button variant="destructive" onClick={handleReject} disabled={loading}>
                                   {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : "Confirm Rejection"}
                               </Button>
                           </div>
                       </div>
                   )}
               </div>
           ) : null}
        </div>

        <DialogFooter className="sm:justify-start">
             <Button variant="outline" onClick={() => onOpenChange(false)}>Close</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
