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

const SPECIAL_OPTIONS = ["NON-CLIENT", "Inquiry", "General", "Vendor"];

interface CallLogDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  associations?: { id: string; name: string }[];
  callLog?: any;
  onSaved?: () => void;
  onSuccess?: () => void;
}

export function CallLogDialog({ open, onOpenChange, associations: propAssociations, callLog, onSaved, onSuccess }: CallLogDialogProps) {
  const { toast } = useToast();
  const { user } = useAuth();
  const [associations, setAssociations] = useState<{ id: string; name: string }[]>(propAssociations || []);
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({
    association_id: "",
    caller_name: "",
    caller_phone: "",
    call_type: "inbound",
    status: "pending",
    duration: "",
    notes: "",
  });

  useEffect(() => {
    if (open && !propAssociations) {
      const fetchAssociations = async () => {
        try {
          const { data, error } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
          if (error) throw error;
          setAssociations(data || []);
        } catch (error) {
          console.error('Error fetching associations:', error);
        }
      };
      fetchAssociations();
    } else if (propAssociations) {
      setAssociations(propAssociations);
    }
  }, [open, propAssociations]);

  useEffect(() => {
    if (callLog) {
      setForm({
        association_id: callLog.association_id || '',
        caller_name: callLog.caller_name || '',
        caller_phone: callLog.caller_phone || '',
        call_type: callLog.call_type || 'inbound',
        status: callLog.status || 'pending',
        duration: callLog.duration || '',
        notes: callLog.notes || '',
      });
    } else {
      setForm({
        association_id: "",
        caller_name: "",
        caller_phone: "",
        call_type: "inbound",
        status: "pending",
        duration: "",
        notes: "",
      });
    }
  }, [callLog, open]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      if (!user) throw new Error('You must be logged in.');

      let finalAssocId = form.association_id;
      let finalNotes = form.notes;

      if (SPECIAL_OPTIONS.includes(form.association_id)) {
        finalAssocId = "";
        finalNotes = `[${form.association_id}] ${form.notes}`;
      }

      // Need a valid association_id for the FK constraint
      const assocId = finalAssocId || (associations.length ? associations[0].id : null);
      if (!assocId || SPECIAL_OPTIONS.includes(form.association_id)) {
        // For special options, still need an association
        if (!associations.length) {
          toast({ title: "Error", description: "No associations available", variant: "destructive" });
          return;
        }
      }

      const dataToSubmit: any = {
        association_id: SPECIAL_OPTIONS.includes(form.association_id) ? associations[0]?.id : assocId,
        caller_name: form.caller_name || "Unknown",
        caller_phone: form.caller_phone || null,
        call_type: form.call_type,
        notes: finalNotes || null,
        follow_up_required: form.status === "pending",
        taken_by: user.id,
      };

      const { error } = callLog
        ? await supabase.from("call_logs").update(dataToSubmit).eq("id", callLog.id)
        : await supabase.from("call_logs").insert(dataToSubmit);

      if (error) throw error;

      toast({ title: callLog ? "Log Updated" : "Communication log created" });
      setForm({ association_id: "", caller_name: "", caller_phone: "", call_type: "inbound", status: "pending", duration: "", notes: "" });
      onOpenChange(false);
      onSaved?.();
      onSuccess?.();
    } catch (error: any) {
      console.error('CallLogDialog error:', error);
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>{callLog ? 'Edit Communication Log' : 'Add New Communication Log'}</DialogTitle>
          <DialogDescription>
            {callLog ? 'Update the details for this communication.' : 'Fill out the form to add a new communication record.'}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label>Client / Category <span className="text-destructive">*</span></Label>
            <Select value={form.association_id} onValueChange={(v) => setForm({ ...form, association_id: v })}>
              <SelectTrigger><SelectValue placeholder="Select a client or category" /></SelectTrigger>
              <SelectContent>
                {SPECIAL_OPTIONS.map((opt) => (
                  <SelectItem key={opt} value={opt}>{opt}</SelectItem>
                ))}
                {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
              </SelectContent>
            </Select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>Caller Name</Label>
              <Input value={form.caller_name} onChange={(e) => setForm({ ...form, caller_name: e.target.value })} placeholder="Enter caller's name" />
            </div>
            <div>
              <Label>Caller Number</Label>
              <Input value={form.caller_phone} onChange={(e) => setForm({ ...form, caller_phone: e.target.value })} placeholder="Enter phone number" />
            </div>
          </div>
          <div className="grid grid-cols-3 gap-4">
            <div>
              <Label>Type <span className="text-destructive">*</span></Label>
              <Select value={form.call_type} onValueChange={(v) => setForm({ ...form, call_type: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="inbound">Inbound</SelectItem>
                  <SelectItem value="outbound">Outbound</SelectItem>
                  <SelectItem value="email">Email</SelectItem>
                  <SelectItem value="voicemail">Voicemail</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Status</Label>
              <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="responded">Responded</SelectItem>
                  <SelectItem value="resolved">Resolved</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Duration (mins)</Label>
              <Input type="number" value={form.duration} onChange={(e) => setForm({ ...form, duration: e.target.value })} />
            </div>
          </div>
          <div>
            <Label>Notes</Label>
            <Textarea value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} placeholder="Enter call notes..." rows={4} />
          </div>
          <div className="flex justify-end space-x-2 pt-4">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={loading}>
              {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {loading ? 'Saving...' : callLog ? 'Update' : 'Create'}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export default CallLogDialog;
