import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { supabase } from '@/integrations/supabase/client';
import { Loader2 } from 'lucide-react';

export default function IndividualOwnerEditDialog({ open, onOpenChange, owner, onSuccess }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    owner_name: '',
    phone_number: '',
    unit_id: ''
  });

  useEffect(() => {
    if (owner) {
      setFormData({
        owner_name: owner.owner_name || '',
        phone_number: owner.phone_number || '',
        unit_id: owner.unit_id || ''
      });
    }
  }, [owner]);

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

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

    setLoading(true);
    try {
      const { error } = await supabase
        .from('owners')
        .update({
          first_name: formData.owner_name.split(' ')[0] || '',
          last_name: formData.owner_name.split(' ').slice(1).join(' ') || '',
          phone: formData.phone_number,
          unit_id: formData.unit_id || null,
          updated_at: new Date().toISOString()
        })
        .eq('id', owner.id);
      
      if (error) throw error;
      
      toast({
        title: "Success",
        description: "Owner details updated successfully."
      });
      if (onSuccess) onSuccess();
      onOpenChange(false);
    } catch (error) {
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to update owner details."
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Edit Individual Owner</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="unit_id">Unit ID</Label>
            <Input
              id="unit_id"
              name="unit_id"
              value={formData.unit_id}
              onChange={handleChange}
              placeholder="Unit 101"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="owner_name">Owner Name</Label>
            <Input
              id="owner_name"
              name="owner_name"
              value={formData.owner_name}
              onChange={handleChange}
              placeholder="Full Name"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="phone_number">Phone Number</Label>
            <Input
              id="phone_number"
              name="phone_number"
              value={formData.phone_number}
              onChange={handleChange}
              placeholder="(555) 123-4567"
            />
          </div>
          <DialogFooter>
            <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" />}
              Save Changes
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
