import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Loader2, Save, Trash2, Mail, Phone, Building } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export default function AssociationDetailsDialog({ open, onOpenChange, association, onSuccess }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [showDeleteAlert, setShowDeleteAlert] = useState(false);

  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    state: '',
    zip: ''
  });

  useEffect(() => {
    if (open && association) {
      setFormData({
        name: association.name || '',
        email: association.email || '',
        phone: association.phone || '',
        address: association.address || '',
        city: association.city || '',
        state: association.state || '',
        zip: association.zip || ''
      });
    }
  }, [open, association]);

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSave = async () => {
    if (!association) return;

    if (!formData.name.trim()) {
      toast({ variant: "destructive", title: "Validation Error", description: "Association name is required." });
      return;
    }

    setLoading(true);
    try {
      const { error } = await supabase
        .from('associations')
        .update({
          name: formData.name,
          email: formData.email,
          phone: formData.phone,
          address: formData.address,
          city: formData.city,
          state: formData.state,
          zip: formData.zip,
          updated_at: new Date().toISOString()
        })
        .eq('id', association.id);

      if (error) throw error;

      toast({ title: "Success", description: "Association details updated successfully." });
      if (onSuccess) onSuccess('update');
      onOpenChange(false);

    } catch (error) {
      console.error('Error updating association:', error);
      toast({ variant: "destructive", title: "Error", description: error.message || "Failed to update association." });
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!association) return;
    setIsDeleting(true);
    try {
        const { error } = await supabase
            .from('associations')
            .delete()
            .eq('id', association.id);

        if (error) throw error;

        toast({ title: "Success", description: "Association deleted successfully." });
        if (onSuccess) onSuccess('delete');
        setShowDeleteAlert(false);
        onOpenChange(false);

    } catch (error) {
        console.error('Error deleting association:', error);
        toast({ variant: "destructive", title: "Error", description: error.message || "Failed to delete association." });
    } finally {
        setIsDeleting(false);
    }
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[550px]">
          <DialogHeader>
            <DialogTitle>Edit Association Details</DialogTitle>
            <DialogDescription>
              Update basic information for <strong>{association?.name}</strong>.
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-6 py-4">
            <div className="grid gap-2">
              <Label htmlFor="name" className="flex items-center gap-2">
                <Building className="w-3.5 h-3.5 text-muted-foreground" />
                Association Name
              </Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => handleChange('name', e.target.value)}
                placeholder="e.g. Sunset Valley HOA"
                className="h-10"
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="email" className="flex items-center gap-2">
                  <Mail className="w-3.5 h-3.5 text-muted-foreground" />
                  Email Address
                </Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => handleChange('email', e.target.value)}
                  placeholder="contact@example.com"
                  className="h-10"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="phone" className="flex items-center gap-2">
                  <Phone className="w-3.5 h-3.5 text-muted-foreground" />
                  Phone Number
                </Label>
                <Input
                  id="phone"
                  value={formData.phone}
                  onChange={(e) => handleChange('phone', e.target.value)}
                  placeholder="(555) 123-4567"
                  className="h-10"
                />
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="address">Address</Label>
              <Input
                id="address"
                value={formData.address}
                onChange={(e) => handleChange('address', e.target.value)}
                placeholder="123 Main St"
                className="h-10"
              />
            </div>

            <div className="grid grid-cols-3 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="city">City</Label>
                <Input id="city" value={formData.city} onChange={(e) => handleChange('city', e.target.value)} className="h-10" />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="state">State</Label>
                <Input id="state" value={formData.state} onChange={(e) => handleChange('state', e.target.value)} className="h-10" />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="zip">Zip</Label>
                <Input id="zip" value={formData.zip} onChange={(e) => handleChange('zip', e.target.value)} className="h-10" />
              </div>
            </div>
          </div>

          <DialogFooter className="flex flex-col-reverse sm:flex-row sm:justify-between items-center gap-2 sm:gap-0">
            <div className="flex-1 flex justify-start w-full sm:w-auto mt-2 sm:mt-0">
              <Button 
                variant="outline" 
                onClick={() => setShowDeleteAlert(true)} 
                type="button"
                className="text-destructive hover:text-destructive w-full sm:w-auto"
              >
                <Trash2 className="w-4 h-4 mr-2" />
                Delete Association
              </Button>
            </div>
            <div className="flex gap-2 w-full sm:w-auto justify-end">
              <Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
                Cancel
              </Button>
              <Button onClick={handleSave} disabled={loading}>
                {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {!loading && <Save className="w-4 h-4 mr-2" />}
                Save Changes
              </Button>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog open={showDeleteAlert} onOpenChange={setShowDeleteAlert}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete the association
              <span className="font-semibold"> {association?.name}</span> and remove all associated data.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction 
              onClick={(e) => { 
                e.preventDefault(); 
                handleDelete(); 
              }} 
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90" 
              disabled={isDeleting}
            >
              {isDeleting ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Trash2 className="w-4 h-4 mr-2" />}
              Delete Association
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
