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

interface CompanyData {
  id: string;
  name: string;
  domain: string | null;
  website: string | null;
  industry: string | null;
  phone: string | null;
  street: string | null;
  postal_code: string | null;
  city: string | null;
  country: string | null;
  notes: string | null;
}

interface Props {
  open: boolean;
  onOpenChange: (o: boolean) => void;
  company: CompanyData;
  onSaved: () => void;
}

export function EditCompanyModal({ open, onOpenChange, company, onSaved }: Props) {
  const { toast } = useToast();
  const [saving, setSaving] = useState(false);
  const [form, setForm, clearDraft] = useDraft(
    `edit-company:${company?.id || 'new'}`,
    {
      name: '', domain: '', website: '', industry: '', phone: '',
      street: '', postal_code: '', city: '', country: '', notes: '',
    },
    open,
  );

  useEffect(() => {
    if (open && company) {
      // If no draft exists for this company, hydrate with current DB values
      const hasDraft = (() => {
        try { return !!window.localStorage.getItem(`draft:edit-company:${company.id}`); }
        catch { return false; }
      })();
      if (!hasDraft) {
        setForm({
          name: company.name || '',
          domain: company.domain || '',
          website: company.website || '',
          industry: company.industry || '',
          phone: company.phone || '',
          street: company.street || '',
          postal_code: company.postal_code || '',
          city: company.city || '',
          country: company.country || '',
          notes: company.notes || '',
        });
      }
    }
  }, [open, company, setForm]);

  const set = (k: string, v: string) => setForm((p) => ({ ...p, [k]: v }));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name.trim()) {
      toast({ title: 'Namn krävs', variant: 'destructive' });
      return;
    }
    setSaving(true);
    const address = [
      form.street.trim(),
      [form.postal_code.trim(), form.city.trim()].filter(Boolean).join(' '),
      form.country.trim(),
    ].filter(Boolean).join(', ') || null;

    const { error } = await supabase.from('companies').update({
      name: form.name.trim(),
      domain: form.domain.trim().toLowerCase() || null,
      website: form.website.trim() || null,
      industry: form.industry.trim() || null,
      phone: form.phone.trim() || null,
      street: form.street.trim() || null,
      postal_code: form.postal_code.trim() || null,
      city: form.city.trim() || null,
      country: form.country.trim() || null,
      address,
      notes: form.notes.trim() || null,
    }).eq('id', company.id);
    setSaving(false);
    if (error) {
      toast({ title: 'Fel', description: error.message, variant: 'destructive' });
      return;
    }
    toast({ title: '✅ Företag uppdaterat' });
    clearDraft();
    onOpenChange(false);
    onSaved();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="bg-card border-border max-w-md max-h-[90vh] flex flex-col p-0">
        <DialogHeader className="px-6 pt-6">
          <DialogTitle className="flex items-center gap-2">
            <Building2 className="h-5 w-5" /> Redigera företag
          </DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0">
          <div className="space-y-4 overflow-y-auto px-6 py-4 flex-1 overscroll-contain">
            <div className="space-y-2">
              <Label>Företagsnamn *</Label>
              <Input value={form.name} onChange={(e) => set('name', e.target.value)} className="bg-secondary border-border" />
            </div>
            <div className="space-y-2">
              <Label>Webbplats</Label>
              <Input value={form.website} onChange={(e) => set('website', e.target.value)} placeholder="https://example.com" className="bg-secondary border-border" />
            </div>
            <div className="space-y-2">
              <Label>Bransch</Label>
              <Input value={form.industry} onChange={(e) => set('industry', e.target.value)} className="bg-secondary border-border" />
            </div>
            <div className="space-y-2">
              <Label>Telefon</Label>
              <Input value={form.phone} onChange={(e) => set('phone', e.target.value)} className="bg-secondary border-border" />
            </div>
            <div className="space-y-2">
              <Label>Gatuadress</Label>
              <Input value={form.street} onChange={(e) => set('street', e.target.value)} className="bg-secondary border-border" />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label>Postnummer</Label>
                <Input value={form.postal_code} onChange={(e) => set('postal_code', e.target.value)} className="bg-secondary border-border" />
              </div>
              <div className="space-y-2">
                <Label>Ort</Label>
                <Input value={form.city} onChange={(e) => set('city', e.target.value)} className="bg-secondary border-border" />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Land</Label>
              <Input value={form.country} onChange={(e) => set('country', e.target.value)} className="bg-secondary border-border" />
            </div>
            <div className="space-y-2">
              <Label>Anteckningar</Label>
              <Textarea value={form.notes} onChange={(e) => set('notes', e.target.value)} rows={3} className="bg-secondary border-border" />
            </div>
          </div>
          <div className="flex justify-end gap-3 px-6 pb-6 pt-3 border-t border-border">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Avbryt</Button>
            <Button type="submit" disabled={saving}>
              {saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Save className="h-4 w-4 mr-2" />}
              {saving ? 'Sparar...' : 'Spara'}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
