import { useState } from 'react';
import { useDraft } from '@/hooks/useDraft';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} 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 { UserPlus } from 'lucide-react';
import { TitleCombobox } from '@/components/dashboard/TitleCombobox';

interface AddContactModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  companyId: string;
  onContactAdded: () => void;
}

export default function AddContactModal({
  open,
  onOpenChange,
  companyId,
  onContactAdded,
}: AddContactModalProps) {
  const { toast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData, clearDraft] = useDraft(
    `add-contact:${companyId}`,
    {
      first_name: '',
      last_name: '',
      email: '',
      direct_phone: '',
      mobile_phone: '',
      title: '',
      notes: '',
    },
    open,
  );

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.email.trim()) {
      toast({
        title: 'Fel',
        description: 'E-post är obligatoriskt',
        variant: 'destructive',
      });
      return;
    }

    setIsSubmitting(true);

    const fullName = [formData.first_name.trim(), formData.last_name.trim()]
      .filter(Boolean)
      .join(' ') || null;

    const { error } = await supabase.from('contacts').insert({
      company_id: companyId,
      first_name: formData.first_name.trim() || null,
      last_name: formData.last_name.trim() || null,
      name: fullName,
      email: formData.email.trim(),
      direct_phone: formData.direct_phone.trim() || null,
      mobile_phone: formData.mobile_phone.trim() || null,
      phone: formData.mobile_phone.trim() || formData.direct_phone.trim() || null,
      title: formData.title.trim() || null,
      notes: formData.notes.trim() || null,
    });

    setIsSubmitting(false);

    if (error) {
      console.error('Error adding contact:', error);
      toast({
        title: 'Fel',
        description: error.message || 'Kunde inte lägga till kontakt',
        variant: 'destructive',
      });
      return;
    }

    const displayName = [formData.first_name, formData.last_name].filter(Boolean).join(' ');
    toast({
      title: 'Kontakt tillagd',
      description: `${displayName || formData.email} har lagts till`,
    });

    setFormData({ first_name: '', last_name: '', email: '', direct_phone: '', mobile_phone: '', title: '', notes: '' });
    clearDraft();
    onOpenChange(false);
    onContactAdded();
  };

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  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" />
            Lägg till kontaktperson
          </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 htmlFor="first_name">Förnamn</Label>
              <Input
                id="first_name"
                value={formData.first_name}
                onChange={(e) => handleChange('first_name', e.target.value)}
                placeholder="Anna"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="last_name">Efternamn</Label>
              <Input
                id="last_name"
                value={formData.last_name}
                onChange={(e) => handleChange('last_name', e.target.value)}
                placeholder="Andersson"
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="title">Titel</Label>
            <TitleCombobox
              id="title"
              value={formData.title}
              onChange={(val) => handleChange('title', val)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">E-post *</Label>
            <Input
              id="email"
              type="email"
              required
              value={formData.email}
              onChange={(e) => handleChange('email', e.target.value)}
              placeholder="namn@foretag.se"
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="direct_phone">Direktnummer</Label>
              <Input
                id="direct_phone"
                type="tel"
                value={formData.direct_phone}
                onChange={(e) => handleChange('direct_phone', e.target.value)}
                placeholder="+46 8 123 45 67"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="mobile_phone">Mobilnummer</Label>
              <Input
                id="mobile_phone"
                type="tel"
                value={formData.mobile_phone}
                onChange={(e) => handleChange('mobile_phone', e.target.value)}
                placeholder="+46 70 123 45 67"
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="notes">Anteckningar</Label>
            <Textarea
              id="notes"
              value={formData.notes}
              onChange={(e) => handleChange('notes', e.target.value)}
              placeholder="Valfria anteckningar..."
              rows={2}
            />
          </div>
          </div>
          <DialogFooter className="px-6 pb-6 pt-2 border-t border-border">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Avbryt
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? 'Sparar...' : 'Lägg till'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
