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

function InvoiceSettingsDialog({ open, onOpenChange, onSettingsUpdated }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  
  const [formData, setFormData] = useState({
    id: null,
    business_name: '',
    address: '',
    phone: '',
    email: '',
    website: '',
    logo_url: ''
  });

  useEffect(() => {
    if (open) {
      fetchSettings();
    }
  }, [open]);

  const fetchSettings = async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from('invoice_settings')
      .select('*')
      .limit(1)
      .maybeSingle();
    
    if (data) {
      setFormData({
        ...data,
        logo_url: data.logo_url || '',
        business_name: data.business_name || '',
        address: data.address || '',
        phone: data.phone || '',
        email: data.email || '',
        website: data.website || ''
      });
    } else if (error) {
      toast({
        variant: "destructive",
        title: "Error fetching settings",
        description: error.message
      });
    }
    setLoading(false);
  };

  const handleFileChange = async (e) => {
    if (!e.target.files || !e.target.files[0]) return;
    
    const file = e.target.files[0];
    const fileExt = file.name.split('.').pop();
    const fileName = `logo-${Date.now()}.${fileExt}`;

    setUploading(true);
    
    try {
      const { error: uploadError } = await supabase.storage
        .from('company-assets')
        .upload(fileName, file);

      if (uploadError) throw uploadError;

      const { data: urlData } = supabase.storage
        .from('company-assets')
        .getPublicUrl(fileName);

      setFormData(prev => ({ ...prev, logo_url: urlData.publicUrl }));
      toast({ title: "Logo uploaded successfully" });
    } catch (error) {
      toast({
        variant: "destructive",
        title: "Upload failed",
        description: error.message
      });
    } finally {
      setUploading(false);
    }
  };

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

    const dataToSave = {
      business_name: formData.business_name,
      address: formData.address,
      phone: formData.phone,
      email: formData.email,
      website: formData.website,
      logo_url: formData.logo_url,
      updated_at: new Date().toISOString()
    };

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

    if (!error) {
      toast({ title: "Settings Saved", description: "Invoice settings have been updated." });
      if (onSettingsUpdated) onSettingsUpdated();
      onOpenChange(false);
    } else {
      toast({ variant: "destructive", title: "Error", description: error.message });
    }

    setLoading(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Invoice Settings</DialogTitle>
          <DialogDescription>Configure your business details and logo for generated invoices.</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="flex flex-col items-center justify-center space-y-2">
            <div className="w-full h-32 border-2 border-dashed border-border rounded-lg flex items-center justify-center overflow-hidden bg-muted relative group">
              {uploading ? (
                <Loader2 className="w-8 h-8 text-muted-foreground animate-spin" />
              ) : formData.logo_url ? (
                <img src={formData.logo_url} alt="Logo Preview" className="w-full h-full object-contain p-2" 
                  onError={(e) => { e.target.onerror = null; e.target.src = "https://placehold.co/400x200?text=Logo+Error"; }} />
              ) : (
                <ImageIcon className="w-8 h-8 text-muted-foreground" />
              )}
              <label className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer text-white text-xs font-medium">
                {uploading ? '' : 'Upload New Logo'}
                <input type="file" accept="image/*" className="hidden" onChange={handleFileChange} disabled={uploading}/>
              </label>
            </div>
            <span className="text-xs text-muted-foreground">Business Logo</span>
          </div>

          <div className="space-y-2">
            <Label htmlFor="logo_url">Logo URL (Optional)</Label>
            <Input id="logo_url" value={formData.logo_url || ''} onChange={(e) => setFormData({ ...formData, logo_url: e.target.value })} placeholder="https://..." className="text-xs" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="business_name">Business Name</Label>
            <Input id="business_name" value={formData.business_name || ''} onChange={(e) => setFormData({ ...formData, business_name: e.target.value })} placeholder="Your Business Name" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="phone">Phone</Label>
              <Input id="phone" value={formData.phone || ''} onChange={(e) => setFormData({ ...formData, phone: e.target.value })} placeholder="(555) 123-4567" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" value={formData.email || ''} onChange={(e) => setFormData({ ...formData, email: e.target.value })} placeholder="info@example.com" />
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="website">Website</Label>
            <Input id="website" value={formData.website || ''} onChange={(e) => setFormData({ ...formData, website: e.target.value })} placeholder="example.com" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="address">Address</Label>
            <Textarea id="address" value={formData.address || ''} onChange={(e) => setFormData({ ...formData, address: e.target.value })} placeholder="Full business address..." rows={3} />
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={loading || uploading}>
              {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
              {loading ? 'Saving...' : 'Save Settings'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export default InvoiceSettingsDialog;
