import { useEffect, useState } from 'react';
import { UserPlus, 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 { TitleCombobox } from '@/components/dashboard/TitleCombobox';
import { useDraft } from '@/hooks/useDraft';

interface ContactData {
  id: string;
  first_name: string | null;
  last_name: string | null;
  email: string;
  direct_phone: string | null;
  mobile_phone: string | null;
  title: string | null;
  notes?: string | null;
}

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

export function EditContactModal({ open, onOpenChange, contact, onSaved }: Props) {
  const { toast } = useToast();
  const [saving, setSaving] = useState(false);
  const [form, setForm, clearDraft] = useDraft(
    `edit-contact:${contact?.id || 'new'}`,
    {
      first_name: '', last_name: '', email: '',
      direct_phone: '', mobile_phone: '', title: '', notes: '',
    },
    open,
  );

  useEffect(() => {
    if (open && contact) {
      const hasDraft = (() => {
        try { return !!window.localStorage.getItem(`draft:edit-contact:${contact.id}`); }
        catch { return false; }
      })();
      if (!hasDraft) {
        setForm({
          first_name: contact.first_name || '',
          last_name: contact.last_name || '',
          email: contact.email || '',
          direct_phone: contact.direct_phone || '',
          mobile_phone: contact.mobile_phone || '',
          title: contact.title || '',
          notes: contact.notes || '',
        });
      }
    }
  }, [open, contact, setForm]);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.email.trim()) {
      toast({ title: 'E-post krävs', variant: 'destructive' });
      return;
    }
    setSaving(true);
    const fullName = [form.first_name.trim(), form.last_name.trim()].filter(Boolean).join(' ') || null;

    const { error } = await supabase.from('contacts').update({
      first_name: form.first_name.trim() || null,
      last_name: form.last_name.trim() || null,
      name: fullName,
      email: form.email.trim(),
      direct_phone: form.direct_phone.trim() || null,
      mobile_phone: form.mobile_phone.trim() || null,
      phone: form.mobile_phone.trim() || form.direct_phone.trim() || null,
      title: form.title.trim() || null,
      notes: form.notes.trim() || null,
    }).eq('id', contact.id);

    setSaving(false);
    if (error) {
      toast({ title: 'Fel', description: error.message, variant: 'destructive' });
      return;
    }
    toast({ title: '✅ Kontakt uppdaterad' });
    clearDraft();
    onOpenChange(false);
    onSaved();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md max-h-[90vh] flex flex-col p-0">
        <DialogHeader className="px-6 pt-6">
          <DialogTitle className="flex items-center gap-2">
            <UserPlus className="h-5 w-5" /> Redigera kontakt
          </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="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Förnamn</Label>
                <Input value={form.first_name} onChange={(e) => set('first_name', e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Efternamn</Label>
                <Input value={form.last_name} onChange={(e) => set('last_name', e.target.value)} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Titel</Label>
              <TitleCombobox value={form.title} onChange={(v) => set('title', v)} />
            </div>
            <div className="space-y-2">
              <Label>E-post *</Label>
              <Input type="email" required value={form.email} onChange={(e) => set('email', e.target.value)} />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Direktnummer</Label>
                <Input type="tel" value={form.direct_phone} onChange={(e) => set('direct_phone', e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Mobilnummer</Label>
                <Input type="tel" value={form.mobile_phone} onChange={(e) => set('mobile_phone', e.target.value)} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Anteckningar</Label>
              <Textarea value={form.notes} onChange={(e) => set('notes', e.target.value)} rows={2} />
            </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>
  );
}
