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

export default function ProjectDialog({ open, onOpenChange, project, onSaved }) {
  const { user } = useAuth();
  const { toast } = useToast();
  const isEditing = !!project;

  const [formData, setFormData] = useState({
    title: '', description: '', status: 'active', budget: '', timeline: '',
    client_id: 'none', assigned_client_ids: [], assigned_board_member_ids: [], assigned_property_ids: []
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [clients, setClients] = useState([]);
  const [boardMembers, setBoardMembers] = useState([]);

  useEffect(() => {
    if (open) {
      if (project) {
        setFormData({
          title: project.title || '', description: project.description || '', status: project.status || 'active',
          budget: project.budget || '', timeline: project.timeline || '', client_id: project.client_id || 'none',
          assigned_client_ids: project.assigned_client_ids || [],
          assigned_board_member_ids: project.assigned_board_member_ids || [],
          assigned_property_ids: project.assigned_property_ids || []
        });
      } else {
        setFormData({ title: '', description: '', status: 'active', budget: '', timeline: '', client_id: 'none', assigned_client_ids: [], assigned_board_member_ids: [], assigned_property_ids: [] });
      }
      fetchOptions();
    }
  }, [open, project]);

  const fetchOptions = async () => {
    try {
      const [clientsRes, membersRes] = await Promise.all([
        supabase.from('associations').select('id, name').eq('status', 'active').order('name'),
        supabase.from('board_members').select('id, member_name')
      ]);
      if (clientsRes.data) setClients(clientsRes.data);
      if (membersRes.data) setBoardMembers(membersRes.data);
    } catch (error) { console.error("Error fetching options:", error); }
  };

  const handleChange = (field, value) => setFormData(prev => ({ ...prev, [field]: value }));
  const toggleArrayItem = (field, id) => {
    setFormData(prev => {
      const arr = prev[field] || [];
      return { ...prev, [field]: arr.includes(id) ? arr.filter(i => i !== id) : [...arr, id] };
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.title.trim()) { toast({ title: "Validation Error", description: "Project name is required.", variant: "destructive" }); return; }
    if (!formData.description.trim()) { toast({ title: "Validation Error", description: "Description is required.", variant: "destructive" }); return; }

    setIsSubmitting(true);
    try {
      const payload = {
        title: formData.title, description: formData.description, status: formData.status,
        budget: formData.budget ? parseFloat(formData.budget) : null,
        timeline: formData.timeline || null,
        client_id: formData.client_id === 'none' ? null : formData.client_id,
        assigned_client_ids: formData.assigned_client_ids,
        assigned_board_member_ids: formData.assigned_board_member_ids,
        assigned_property_ids: formData.assigned_property_ids
      };
      if (!isEditing) payload.created_by = user?.id;

      let error;
      if (isEditing) {
        const res = await supabase.from('projects').update(payload).eq('id', project.id);
        error = res.error;
      } else {
        const res = await supabase.from('projects').insert([payload]);
        error = res.error;
      }
      if (error) throw error;
      toast({ title: "Success", description: `Project ${isEditing ? 'updated' : 'created'} successfully.` });
      onSaved(); onOpenChange(false);
    } catch (error) {
      console.error("Error saving project:", error);
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } finally { setIsSubmitting(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{isEditing ? 'Edit Project' : 'Create New Project'}</DialogTitle>
          <DialogDescription>{isEditing ? 'Update project details and assignments.' : 'Add a new project to track progress.'}</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-6 py-4">
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="title">Project Name <span className="text-destructive">*</span></Label>
              <Input id="title" placeholder="e.g., Roof Replacement 2026" value={formData.title} onChange={(e) => handleChange('title', e.target.value)} required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="description">Description <span className="text-destructive">*</span></Label>
              <Textarea id="description" placeholder="Briefly describe the project goals..." value={formData.description} onChange={(e) => handleChange('description', e.target.value)} className="min-h-[100px]" required />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="status">Status</Label>
                <Select value={formData.status} onValueChange={(v) => handleChange('status', v)}>
                  <SelectTrigger><SelectValue placeholder="Select Status" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">Active</SelectItem><SelectItem value="on_hold">On Hold</SelectItem>
                    <SelectItem value="completed">Completed</SelectItem><SelectItem value="cancelled">Cancelled</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="budget">Budget ($) <span className="text-muted-foreground font-normal text-xs">(Optional)</span></Label>
                <Input id="budget" type="number" step="0.01" min="0" placeholder="0.00" value={formData.budget} onChange={(e) => handleChange('budget', e.target.value)} />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="timeline">Timeline / Schedule <span className="text-muted-foreground font-normal text-xs">(Optional)</span></Label>
              <Input id="timeline" placeholder="e.g., Q3 2026 - Q4 2026" value={formData.timeline} onChange={(e) => handleChange('timeline', e.target.value)} />
            </div>
          </div>

          <div className="space-y-6 pt-4 border-t">
            <h3 className="text-lg font-semibold">Assignments</h3>
            <div className="space-y-2">
              <Label>Primary Association</Label>
              <Select value={formData.client_id} onValueChange={(v) => handleChange('client_id', v)}>
                <SelectTrigger><SelectValue placeholder="Select Primary Association" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">None</SelectItem>
                  {clients.map(c => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Assigned Associations</Label>
                <div className="border rounded-md p-2 h-40 overflow-y-auto bg-muted/50">
                  {clients.map(c => (
                    <div key={c.id} className="flex items-center space-x-2 py-1">
                      <Checkbox id={`client-${c.id}`} checked={(formData.assigned_client_ids || []).includes(c.id)} onCheckedChange={() => toggleArrayItem('assigned_client_ids', c.id)} />
                      <Label htmlFor={`client-${c.id}`} className="text-sm font-normal cursor-pointer">{c.name}</Label>
                    </div>
                  ))}
                </div>
              </div>
              <div className="space-y-2">
                <Label>Assigned Board Members</Label>
                <div className="border rounded-md p-2 h-40 overflow-y-auto bg-muted/50">
                  {boardMembers.map(b => (
                    <div key={b.id} className="flex items-center space-x-2 py-1">
                      <Checkbox id={`board-${b.id}`} checked={(formData.assigned_board_member_ids || []).includes(b.id)} onCheckedChange={() => toggleArrayItem('assigned_board_member_ids', b.id)} />
                      <Label htmlFor={`board-${b.id}`} className="text-sm font-normal cursor-pointer">{b.member_name || 'Unnamed'}</Label>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <DialogFooter className="pt-4 border-t">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
              {isEditing ? 'Save Changes' : 'Create Project'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
