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

const ESTOPPEL_STAGES = [
  "Estoppel Requested",
  "Estoppel Received",
  "Estoppel Issued",
  "Closing Documents Received"
];

function EstoppelDialog({ open, onOpenChange, onSuccess, estoppel = null }) {
  const { toast } = useToast();
  const { user } = useAuth();
  const [associations, setAssociations] = useState([]);
  const [loading, setLoading] = useState(false);
  
  const [scopeType, setScopeType] = useState('property');

  const [formData, setFormData] = useState({
    association_id: '',
    address: '',
    status: 'Estoppel Requested',
    notes: '',
  });

  useEffect(() => {
    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('EstoppelDialog.fetchAssociations', error);
      }
    };

    if (open) {
      fetchAssociations();
      if (estoppel) {
        const isAssociationLevel = estoppel.address === 'Association-level';
        setScopeType(isAssociationLevel ? 'association' : 'property');
        
        setFormData({
          association_id: estoppel.association_id,
          address: estoppel.address, 
          status: estoppel.status,
          notes: estoppel.notes || '',
        });
      } else {
        setScopeType('property');
        setFormData({
          association_id: '',
          address: '',
          status: 'Estoppel Requested',
          notes: '',
        });
      }
    }
  }, [open, estoppel]);

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

    try {
      const finalAddress = scopeType === 'association' ? 'Association-level' : formData.address;

      if (!formData.association_id) {
        throw new Error("Association is required.");
      }
      if (scopeType === 'property' && !finalAddress.trim()) {
        throw new Error("Please enter a property address.");
      }

      const dataToSubmit = {
        association_id: formData.association_id,
        address: finalAddress,
        status: formData.status,
        notes: formData.notes,
        created_by: user.id,
        updated_at: new Date().toISOString()
      };

      if (!estoppel) {
        dataToSubmit.created_at = new Date().toISOString();
      }

      let error;
      if (estoppel) {
        const { error: updateError } = await supabase
          .from('estoppels')
          .update(dataToSubmit)
          .eq('id', estoppel.id);
        error = updateError;
      } else {
        const { error: insertError } = await supabase
          .from('estoppels')
          .insert([dataToSubmit]);
        error = insertError;
      }

      if (error) throw error;

      toast({
        title: estoppel ? "Estoppel Updated" : "Estoppel Created",
        description: estoppel ? "Estoppel has been successfully updated." : "Estoppel has been successfully created.",
      });
      onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error('EstoppelDialog.handleSubmit', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>{estoppel ? 'Edit Estoppel' : 'New Estoppel Request'}</DialogTitle>
          <DialogDescription>
            {estoppel ? 'Update estoppel details and status.' : 'Create a new estoppel record.'}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label htmlFor="association_id">Association *</Label>
            <select
              id="association_id"
              value={formData.association_id}
              onChange={(e) => setFormData({ ...formData, association_id: e.target.value })}
              required
              className="w-full mt-1 px-3 py-2 border border-border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-background"
            >
              <option value="">Select an association</option>
              {associations.map((assoc) => (
                <option key={assoc.id} value={assoc.id}>{assoc.name}</option>
              ))}
            </select>
          </div>

          <div className="space-y-2">
            <Label>Request Type</Label>
            <div className="flex space-x-6">
              <label className="flex items-center space-x-2 cursor-pointer">
                <div className="relative flex items-center">
                  <input
                    type="radio"
                    name="scopeType"
                    value="property"
                    checked={scopeType === 'property'}
                    onChange={() => setScopeType('property')}
                    className="peer h-4 w-4 border-border text-primary focus:ring-primary"
                  />
                </div>
                <span className="text-sm font-medium text-foreground">Property Address</span>
              </label>
              <label className="flex items-center space-x-2 cursor-pointer">
                <div className="relative flex items-center">
                  <input
                    type="radio"
                    name="scopeType"
                    value="association"
                    checked={scopeType === 'association'}
                    onChange={() => setScopeType('association')}
                    className="peer h-4 w-4 border-border text-primary focus:ring-primary"
                  />
                </div>
                <span className="text-sm font-medium text-foreground">Association-level</span>
              </label>
            </div>
          </div>

          {scopeType === 'property' && (
            <div>
              <Label htmlFor="address">Address *</Label>
              <input
                id="address"
                type="text"
                value={formData.address}
                onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                required={scopeType === 'property'}
                placeholder="Enter property address"
                className="w-full mt-1 px-3 py-2 border border-border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-background"
              />
            </div>
          )}

          <div>
            <Label htmlFor="status">Current Stage *</Label>
            <select
              id="status"
              value={formData.status}
              onChange={(e) => setFormData({ ...formData, status: e.target.value })}
              required
              className="w-full mt-1 px-3 py-2 border border-border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-background"
            >
              {ESTOPPEL_STAGES.map((stage) => (
                <option key={stage} value={stage}>{stage}</option>
              ))}
            </select>
          </div>

          <div>
            <Label htmlFor="notes">Notes</Label>
            <textarea
              id="notes"
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              rows={3}
              placeholder="Add any additional details..."
              className="w-full mt-1 px-3 py-2 border border-border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-background"
            />
          </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 ? (estoppel ? 'Updating...' : 'Creating...') : (estoppel ? 'Save Changes' : 'Create Record')}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export default EstoppelDialog;
