import { logger } from '@/lib/logger';
import { useState, useEffect } from 'react';
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 { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';
import { useQueryClient } from '@tanstack/react-query';
import { Building } from 'lucide-react';
import { addLeadActivity } from '@/lib/lead-utils';

interface CreateLeadDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  defaultCompanyId?: string;
  defaultCompanyName?: string;
}

export function CreateLeadDialog({ 
  open, 
  onOpenChange, 
  defaultCompanyId,
  defaultCompanyName 
}: CreateLeadDialogProps) {
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const queryClient = useQueryClient();

  const resetForm = () => {
    setEmail('');
    setName('');
    setPhone('');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!email || !email.includes('@')) {
      toast.error('Please enter a valid email address');
      return;
    }

    setIsSubmitting(true);

    try {
      // Check if lead already exists
      const { data: existing } = await supabase
        .from('leads')
        .select('id')
        .eq('email', email.toLowerCase())
        .maybeSingle();

      if (existing) {
        toast.error('A contact with this email already exists');
        setIsSubmitting(false);
        return;
      }

      // Create lead with company_id if provided
      const { data: newLead, error } = await supabase
        .from('leads')
        .insert({
          email: email.toLowerCase(),
          name: name || null,
          company_id: defaultCompanyId || null,
          phone: phone || null,
          source: 'manual',
          status: 'lead',
          score: 0,
          needs_review: false,
        })
        .select()
        .single();

      if (error) throw error;

      // Add initial activity via contract
      await addLeadActivity({
        leadId: newLead.id,
        type: 'note',
        metadata: { text: defaultCompanyId ? `Contact added to company` : 'Contact created manually' },
      });

      toast.success('Contact created');
      queryClient.invalidateQueries({ queryKey: ['leads'] });
      queryClient.invalidateQueries({ queryKey: ['lead-stats'] });
      if (defaultCompanyId) {
        queryClient.invalidateQueries({ queryKey: ['companies', defaultCompanyId, 'leads'] });
      }
      
      resetForm();
      onOpenChange(false);
    } catch (error) {
      logger.error('Failed to create lead:', error);
      toast.error('Could not create contact');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>
            {defaultCompanyName ? `Add Contact to ${defaultCompanyName}` : 'Create New Contact'}
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          {defaultCompanyName && (
            <div className="flex items-center gap-2 p-3 rounded-md bg-muted/50 text-sm">
              <Building className="h-4 w-4 text-muted-foreground" />
              <span>Adding to: <strong>{defaultCompanyName}</strong></span>
            </div>
          )}

          <div className="space-y-2">
            <Label htmlFor="email">Email *</Label>
            <Input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="name@company.com"
              required
              autoFocus
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="name">Name</Label>
            <Input
              id="name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="John Doe"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="phone">Phone</Label>
            <Input
              id="phone"
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+1 234 567 8900"
            />
          </div>

          <p className="text-xs text-muted-foreground">
            New contacts start as <strong>Lead</strong>. Status auto-updates as deals progress
            (Lead → Opportunity → Customer).
          </p>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting ? 'Creating...' : 'Create Contact'}
          </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
