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

function ClientDialog({ open, onOpenChange, onSuccess, client }) {
  const db = supabase;
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    state: '',
    zip: '',
    logo_url: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [uploadingLogo, setUploadingLogo] = useState(false);
  const { toast } = useToast();

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

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

  const handleFileUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    setUploadingLogo(true);
    try {
      const fileExt = file.name.split('.').pop();
      const fileName = `${Date.now()}_${Math.random().toString(36).substring(7)}.${fileExt}`;
      const filePath = `associations/${fileName}`;

      const { error: uploadError } = await supabase.storage
        .from('logos')
        .upload(filePath, file);

      if (uploadError) throw uploadError;

      const { data: { publicUrl } } = supabase.storage
        .from('logos')
        .getPublicUrl(filePath);

      setFormData(prev => ({ ...prev, logo_url: publicUrl }));
      toast({ title: "Upload Successful", description: "Logo uploaded successfully." });

    } catch (error) {
      console.error('Error uploading logo:', error);
      toast({ variant: "destructive", title: "Upload Failed", description: error.message });
    } finally {
      setUploadingLogo(false);
    }
  };

  const removeLogo = () => {
    setFormData(prev => ({ ...prev, logo_url: '' }));
  };

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

    const dataToSubmit = { ...formData };

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

    if (!error) {
      toast({
        title: `Association ${client ? 'Updated' : 'Added'}`,
        description: `Association information has been successfully ${client ? 'updated' : 'added'}.`,
      });
      onSuccess();
      onOpenChange(false);
    } else {
      toast({
        variant: 'destructive',
        title: `Error ${client ? 'updating' : 'adding'} association`,
        description: error.message,
      });
    }
    setIsSubmitting(false);
  };

  const isEditMode = !!client;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-4xl bg-slate-50 text-slate-900 max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-2xl font-bold">{isEditMode ? 'Edit Association' : 'Add New Association'}</DialogTitle>
          <DialogDescription>
            {isEditMode ? 'Update the association\'s details below.' : 'Fill in the details for the new association.'}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-6 py-4">
          {/* Logo Upload Section */}
          <div className="bg-white p-4 rounded-lg border shadow-sm">
            <div className="space-y-2">
              <Label className="font-semibold text-sm">Association Logo</Label>
              <div className="flex flex-col gap-3">
                {formData.logo_url ? (
                  <div className="relative w-full h-32 bg-slate-100 rounded border flex items-center justify-center overflow-hidden group">
                    <img src={formData.logo_url} alt="Logo" className="max-h-full max-w-full object-contain" />
                    <button 
                      type="button" 
                      onClick={removeLogo}
                      className="absolute top-2 right-2 bg-red-100 p-1 rounded-full text-red-600 opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                ) : (
                  <div className="w-full h-32 bg-slate-100 rounded border border-dashed border-slate-300 flex flex-col items-center justify-center text-slate-400">
                    <ImageIcon className="w-8 h-8 mb-2" />
                    <span className="text-xs">No logo uploaded</span>
                  </div>
                )}
                <div className="flex items-center gap-2">
                  <Input 
                    type="file" 
                    accept="image/*" 
                    onChange={handleFileUpload} 
                    className="cursor-pointer text-xs"
                    disabled={uploadingLogo}
                  />
                  {uploadingLogo && <Loader2 className="w-4 h-4 animate-spin" />}
                </div>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="flex flex-col space-y-2">
              <Label htmlFor="name" className="font-semibold text-sm">Name *</Label>
              <Input id="name" name="name" value={formData.name} onChange={handleChange} required className="bg-white" />
            </div>
            <div className="flex flex-col space-y-2">
              <Label htmlFor="email" className="font-semibold text-sm">Email</Label>
              <Input id="email" name="email" type="email" value={formData.email} onChange={handleChange} className="bg-white" />
            </div>
            <div className="flex flex-col space-y-2">
              <Label htmlFor="phone" className="font-semibold text-sm">Phone</Label>
              <Input id="phone" name="phone" value={formData.phone} onChange={handleChange} className="bg-white" />
            </div>
            <div className="flex flex-col space-y-2">
              <Label htmlFor="address" className="font-semibold text-sm">Address</Label>
              <Input id="address" name="address" value={formData.address} onChange={handleChange} className="bg-white" />
            </div>
            <div className="flex flex-col space-y-2">
              <Label htmlFor="city" className="font-semibold text-sm">City</Label>
              <Input id="city" name="city" value={formData.city} onChange={handleChange} className="bg-white" />
            </div>
            <div className="flex flex-col space-y-2">
              <Label htmlFor="state" className="font-semibold text-sm">State</Label>
              <Input id="state" name="state" value={formData.state} onChange={handleChange} className="bg-white" />
            </div>
            <div className="flex flex-col space-y-2">
              <Label htmlFor="zip" className="font-semibold text-sm">Zip</Label>
              <Input id="zip" name="zip" value={formData.zip} onChange={handleChange} className="bg-white" />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
              Cancel
            </Button>
            <Button type="submit" className="bg-blue-900 hover:bg-blue-800" disabled={isSubmitting}>
              {isSubmitting ? 'Saving...' : (isEditMode ? 'Save Changes' : 'Add Association')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export default ClientDialog;