import React, { useState, useEffect } from 'react';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { Loader2, CheckCircle2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';

export default function HomeownerRequestDialog({ open, onOpenChange, request, onSuccess, isReadOnly = false }) {
  const { user } = useAuth();
  const { toast } = useToast();
  
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [status, setStatus] = useState('open');
  const [category, setCategory] = useState('general');
  const [priority, setPriority] = useState('medium');
  const [selectedAssociations, setSelectedAssociations] = useState([]);
  
  const [associations, setAssociations] = useState([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
     const fetchAssociations = async () => {
         setLoading(true);
         const { data } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
         setAssociations(data || []);
         setLoading(false);
     };
     if (open) fetchAssociations();
  }, [open]);

  useEffect(() => {
     if (request) {
        setTitle(request.title || '');
        setDescription(request.description || '');
        setStatus(request.status || 'open');
        setCategory(request.category || 'general');
        setPriority(request.priority || 'medium');
     } else {
        setTitle('');
        setDescription('');
        setStatus('open');
        setCategory('general');
        setPriority('medium');
        setSelectedAssociations([]);
     }
  }, [request, open]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!title.trim()) return toast({ variant: 'destructive', title: 'Title required' });
    if (selectedAssociations.length === 0) return toast({ variant: 'destructive', title: 'Select at least one association' });
    
    setSubmitting(true);
    try {
       const payload = {
           title,
           description,
           status,
           category,
           priority,
           updated_at: new Date().toISOString()
       };
       
       if (request) {
           const { error } = await supabase.from('homeowner_requests').update(payload).eq('id', request.id);
           if (error) throw error;
       } else {
           const { error } = await supabase.from('homeowner_requests')
               .insert({ ...payload, association_id: selectedAssociations[0] });
           if (error) throw error;
       }

       toast({ title: 'Success', description: 'Request saved successfully.' });
       if (onSuccess) onSuccess();
       onOpenChange(false);

    } catch (error) {
       console.error(error);
       toast({ variant: 'destructive', title: 'Error', description: error.message });
    } finally {
       setSubmitting(false);
    }
  };

  const toggleAssociation = (id) => {
     if (isReadOnly) return;
     setSelectedAssociations(prev => 
         prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
     );
  };

  const handleSelectAll = () => {
    if (isReadOnly) return;
    if (selectedAssociations.length === associations.length) {
      setSelectedAssociations([]);
    } else {
      setSelectedAssociations(associations.map(c => c.id));
    }
  };

  if (isReadOnly) {
      return null; 
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[800px] h-[90vh] flex flex-col p-0 gap-0">
        <DialogHeader className="p-6 pb-2">
          <div className="flex justify-between items-start">
             <div>
                <DialogTitle>{request ? 'Edit Homeowner Request' : 'New Homeowner Request'}</DialogTitle> 
                <DialogDescription>Create or edit a homeowner request.</DialogDescription>
             </div>
          </div>
        </DialogHeader>
        
        <ScrollArea className="flex-1 px-6">
           <div className="py-4 space-y-6">
              <div className="space-y-2">
                 <Label>Title <span className="text-destructive">*</span></Label>
                 <Input value={title} onChange={e => setTitle(e.target.value)} placeholder="e.g. Maintenance Request" />
              </div>
              
              <div className="space-y-2">
                 <Label>Description</Label>
                 <Textarea value={description} onChange={e => setDescription(e.target.value)} placeholder="Brief summary..." rows={3} />
              </div>
              
              <div className="grid grid-cols-3 gap-4">
                 <div className="space-y-2">
                    <Label>Status</Label>
                    <Select value={status} onValueChange={setStatus}>
                       <SelectTrigger><SelectValue /></SelectTrigger>
                       <SelectContent>
                          <SelectItem value="open">Open</SelectItem>
                          <SelectItem value="in-progress">In Progress</SelectItem>
                          <SelectItem value="resolved">Resolved</SelectItem>
                          <SelectItem value="closed">Closed</SelectItem>
                       </SelectContent>
                    </Select>
                 </div>
                 <div className="space-y-2">
                    <Label>Category</Label>
                    <Select value={category} onValueChange={setCategory}>
                       <SelectTrigger><SelectValue /></SelectTrigger>
                       <SelectContent>
                          <SelectItem value="general">General</SelectItem>
                          <SelectItem value="maintenance">Maintenance</SelectItem>
                          <SelectItem value="complaint">Complaint</SelectItem>
                          <SelectItem value="architectural">Architectural</SelectItem>
                       </SelectContent>
                    </Select>
                 </div>
                 <div className="space-y-2">
                    <Label>Priority</Label>
                    <Select value={priority} onValueChange={setPriority}>
                       <SelectTrigger><SelectValue /></SelectTrigger>
                       <SelectContent>
                          <SelectItem value="low">Low</SelectItem>
                          <SelectItem value="medium">Medium</SelectItem>
                          <SelectItem value="high">High</SelectItem>
                       </SelectContent>
                    </Select>
                 </div>
              </div>

              <div className="space-y-3">
                 <div className="flex justify-between items-center">
                    <Label>Assigned Associations <span className="text-destructive">*</span></Label>
                    <Button variant="link" size="sm" className="h-auto p-0 text-xs" onClick={handleSelectAll}>
                      {selectedAssociations.length === associations.length ? 'Deselect All' : 'Select All'}
                    </Button>
                 </div>
                 <div className="border rounded-md p-4 max-h-48 overflow-y-auto grid grid-cols-1 sm:grid-cols-2 gap-2 bg-muted">
                    {loading ? <Loader2 className="animate-spin mx-auto" /> : associations.map(assoc => (
                       <div key={assoc.id} className="flex items-center space-x-2">
                          <Checkbox id={assoc.id} checked={selectedAssociations.includes(assoc.id)} onCheckedChange={() => toggleAssociation(assoc.id)} />
                          <label htmlFor={assoc.id} className="text-sm font-medium leading-none cursor-pointer">
                             {assoc.name}
                          </label>
                       </div>
                    ))}
                 </div>
              </div>
           </div>
        </ScrollArea>
        
        <DialogFooter className="p-6 pt-2 border-t">
           <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
           <Button onClick={handleSubmit} disabled={submitting}>
              {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Save Request
           </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
