
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 { Checkbox } from '@/components/ui/checkbox';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { Loader2, Save } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

export default function OwnerDialog({ open, onOpenChange, owner, clientId, onSuccess }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  
  const constructLegacyAddress = (street, city, state, zip) => {
    if (!street && !city && !state && !zip) return '';
    let address = street || '';
    if (city || state || zip) {
      address += '\n';
      const cityLine = [city, state, zip].filter(Boolean).join(' ');
      if (cityLine) address += cityLine;
    }
    return address.trim();
  };

  const [formData, setFormData] = useState({
    account_number: '', unit_id: '', owner_name: '', property_address: '',
    email: '', phone: '', balance: '', electronic_consent: false, show_proxy_text: true,
    mailing_address: '', alt_address_1: '', alt_address_2: '',
  });

  useEffect(() => {
    if (open) {
      if (owner) {
        const initialMailing = owner.mailing_address || constructLegacyAddress(owner.mailing_address_street, owner.mailing_address_city, owner.mailing_address_state, owner.mailing_address_zip);
        const initialAlt1 = owner.alt_address_1 || constructLegacyAddress(owner.alt_address_1_street, owner.alt_address_1_city, owner.alt_address_1_state, owner.alt_address_1_zip);
        const initialAlt2 = owner.alt_address_2 || constructLegacyAddress(owner.alt_address_2_street, owner.alt_address_2_city, owner.alt_address_2_state, owner.alt_address_2_zip);

        setFormData({
          account_number: owner.account_number || '', unit_id: owner.unit_id || '',
          owner_name: owner.owner_name || '', property_address: owner.property_address || '',
          email: owner.email || '', phone: owner.phone || '',
          balance: owner.balance !== undefined && owner.balance !== null ? owner.balance : '',
          electronic_consent: owner.electronic_consent || false,
          show_proxy_text: owner.show_proxy_text !== undefined ? owner.show_proxy_text : true,
          mailing_address: initialMailing, alt_address_1: initialAlt1, alt_address_2: initialAlt2,
        });
      } else {
        setFormData({
          account_number: '', unit_id: '', owner_name: '', property_address: '',
          email: '', phone: '', balance: '', electronic_consent: false, show_proxy_text: true,
          mailing_address: '', alt_address_1: '', alt_address_2: '',
        });
      }
    }
  }, [open, owner]);

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

  const handleSubmit = async () => {
    if (!clientId) return;
    if (!formData.owner_name.trim()) { toast({ variant: "destructive", title: "Error", description: "Owner Name is required." }); return; }
    if (!formData.property_address.trim()) { toast({ variant: "destructive", title: "Error", description: "Property Address is required." }); return; }

    setLoading(true);
    try {
      const { data: existingDuplicate, error: checkError } = await supabase
        .from('property_owners').select('id').eq('client_id', clientId)
        .ilike('property_address', formData.property_address.trim()).maybeSingle();
      if (checkError) throw checkError;
      if (existingDuplicate && (!owner || existingDuplicate.id !== owner.id)) throw new Error("DUPLICATE_ADDRESS");

      const payload = {
        client_id: clientId, account_number: formData.account_number, unit_id: formData.unit_id,
        owner_name: formData.owner_name, property_address: formData.property_address,
        email: formData.email, phone: formData.phone,
        balance: formData.balance === '' ? 0 : parseFloat(formData.balance),
        electronic_consent: formData.electronic_consent, show_proxy_text: formData.show_proxy_text,
        mailing_address: formData.mailing_address || null,
        alt_address_1: formData.alt_address_1 || null, alt_address_2: formData.alt_address_2 || null,
      };

      let error;
      if (owner?.id) {
        const { error: updateError } = await supabase.from('property_owners').update(payload).eq('id', owner.id);
        error = updateError;
      } else {
        const { error: insertError } = await supabase.from('property_owners').insert([payload]);
        error = insertError;
      }
      if (error) throw error;

      toast({ title: "Success", description: owner?.id ? "Owner updated successfully." : "Owner added successfully." });
      onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error("Error saving owner:", error);
      if (error.message === "DUPLICATE_ADDRESS") {
        toast({ variant: "destructive", title: "Duplicate Address", description: "A property with this address already exists." });
      } else if (error.code === '23505') {
        toast({ variant: "destructive", title: "Duplicate Record", description: "A record with this address or account number already exists." });
      } else {
        toast({ variant: "destructive", title: "Error", description: error.message });
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{owner ? "Edit Owner" : "Add New Owner"}</DialogTitle>
          <DialogDescription>{owner ? "Modify the details for this property owner." : "Enter the details for the new property owner."}</DialogDescription>
        </DialogHeader>
        
        <Tabs defaultValue="details" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="details">Owner Details</TabsTrigger>
                <TabsTrigger value="addresses">Addresses</TabsTrigger>
            </TabsList>
            
            <TabsContent value="details" className="space-y-4 py-4">
                <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="account_number">Account Number</Label>
                      <Input id="account_number" value={formData.account_number} onChange={(e) => handleChange('account_number', e.target.value)} placeholder="e.g. A-101" />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="unit_id">Unit ID</Label>
                      <Input id="unit_id" value={formData.unit_id} onChange={(e) => handleChange('unit_id', e.target.value)} placeholder="e.g. 101" />
                    </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="owner_name">Owner Name *</Label>
                  <Input id="owner_name" value={formData.owner_name} onChange={(e) => handleChange('owner_name', e.target.value)} placeholder="John Doe" />
                </div>
                <div className="space-y-2">
                    <Label htmlFor="property_address">Property Address *</Label>
                    <Input id="property_address" value={formData.property_address} onChange={(e) => handleChange('property_address', e.target.value)} placeholder="123 Main St, City, State, Zip" />
                </div>
                <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="email">Email Address</Label>
                      <Input id="email" type="email" value={formData.email} onChange={(e) => handleChange('email', e.target.value)} placeholder="email@example.com" />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="phone">Phone Number</Label>
                      <Input id="phone" value={formData.phone} onChange={(e) => handleChange('phone', e.target.value)} placeholder="(555) 123-4567" />
                    </div>
                </div>
                <div className="space-y-2">
                     <Label htmlFor="balance">Current Balance ($)</Label>
                     <Input id="balance" type="number" step="0.01" value={formData.balance} onChange={(e) => handleChange('balance', e.target.value)} placeholder="0.00" />
                </div>
                <div className="flex flex-col gap-3 pt-2">
                    <div className="flex items-center space-x-2">
                        <Checkbox id="electronic_consent" checked={formData.electronic_consent} onCheckedChange={(checked) => handleChange('electronic_consent', checked)} />
                        <Label htmlFor="electronic_consent" className="cursor-pointer">Electronic Consent Received</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                        <Checkbox id="show_proxy_text" checked={formData.show_proxy_text} onCheckedChange={(checked) => handleChange('show_proxy_text', checked)} />
                        <Label htmlFor="show_proxy_text" className="cursor-pointer">Include Proxy Text on Sign-in Sheet</Label>
                    </div>
                </div>
            </TabsContent>

            <TabsContent value="addresses" className="space-y-4 py-4">
                <div className="space-y-2">
                    <Label htmlFor="mailing_address">Mailing Address (Primary)</Label>
                    <Textarea id="mailing_address" value={formData.mailing_address} onChange={(e) => handleChange('mailing_address', e.target.value)} placeholder={"123 Main St\nCity, State Zip"} className="min-h-[100px]" />
                </div>
                <div className="space-y-2">
                    <Label htmlFor="alt_address_1">Alternate Address 1</Label>
                    <Textarea id="alt_address_1" value={formData.alt_address_1} onChange={(e) => handleChange('alt_address_1', e.target.value)} placeholder={"123 Vacation Ln\nBeach City, FL 33139"} className="min-h-[100px]" />
                </div>
                <div className="space-y-2">
                    <Label htmlFor="alt_address_2">Alternate Address 2</Label>
                    <Textarea id="alt_address_2" value={formData.alt_address_2} onChange={(e) => handleChange('alt_address_2', e.target.value)} placeholder="Another Address..." className="min-h-[100px]" />
                </div>
            </TabsContent>
        </Tabs>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleSubmit} disabled={loading}>
            {loading && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
            <Save className="w-4 h-4 mr-2" />
            {owner ? "Save Changes" : "Add Owner"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
