// ContactFormDialog.tsx
import { useState, useEffect, useMemo } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
    User,
    Mail,
    Phone,
    Building2,
    Globe,
    Loader2,
    UserPlus,
    Save,
    Sparkles,
    AlertCircle,
    CheckCircle2,
    AtSign,
    Hash,
    Link2,
    MapPin,
    Briefcase,
    Tag,
    TrendingUp,
    Users,
    UserCheck,
    UserX,
    ChevronDown,
    Info,
    X,
    Copy,
    ExternalLink,
} from 'lucide-react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import {
    Tabs,
    TabsContent,
    TabsList,
    TabsTrigger,
} from '@/components/ui/tabs';
import {
    Collapsible,
    CollapsibleContent,
    CollapsibleTrigger,
} from '@/components/ui/collapsible';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ContactWithTags, ContactInsert, ContactUpdate } from '@/hooks/useContacts';
import { Database } from '@/integrations/supabase/types';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

type ContactStatus = Database['public']['Enums']['contact_status'];

// Enhanced schema with more fields
const contactFormSchema = z.object({
    // Basic Info
    first_name: z.string().min(1, 'First name is required').max(100),
    last_name: z.string().min(1, 'Last name is required').max(100),
    email: z.string().email('Invalid email address').max(255),
    phone: z.string().max(50).optional().or(z.literal('')),

    // Company Info
    company: z.string().max(200).optional().or(z.literal('')),
    job_title: z.string().max(100).optional().or(z.literal('')),

    // Source & Status
    source: z.string().max(100).optional().or(z.literal('')),
    status: z.enum(['lead', 'prospect', 'customer', 'churned']),

    // Additional Info
    website: z.string().url('Invalid URL').max(255).optional().or(z.literal('')),
    linkedin: z.string().max(255).optional().or(z.literal('')),
    address: z.string().max(500).optional().or(z.literal('')),
    notes: z.string().max(2000).optional().or(z.literal('')),
});

type ContactFormValues = z.infer<typeof contactFormSchema>;

interface ContactFormDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    contact?: ContactWithTags | null;
    onSubmit: (data: ContactInsert | (ContactUpdate & { id: string })) => Promise<void>;
    isSubmitting: boolean;
}

// Status configuration
const statusConfig: Record<ContactStatus, { label: string; icon: React.ElementType; color: string; bg: string; description: string }> = {
    lead: {
        label: 'Lead',
        icon: Users,
        color: 'text-blue-600',
        bg: 'bg-blue-500/10',
        description: 'New potential contact',
    },
    prospect: {
        label: 'Prospect',
        icon: TrendingUp,
        color: 'text-amber-600',
        bg: 'bg-amber-500/10',
        description: 'Actively engaged',
    },
    customer: {
        label: 'Customer',
        icon: UserCheck,
        color: 'text-green-600',
        bg: 'bg-green-500/10',
        description: 'Converted customer',
    },
    churned: {
        label: 'Churned',
        icon: UserX,
        color: 'text-slate-500',
        bg: 'bg-slate-500/10',
        description: 'No longer active',
    },
};

// Source suggestions
const sourceSuggestions = [
    'Website',
    'Referral',
    'LinkedIn',
    'Cold Outreach',
    'Conference',
    'Webinar',
    'Advertisement',
    'Partner',
    'Other',
];

// Phone formatting helper
function formatPhoneInput(value: string): string {
    const numbers = value.replace(/\D/g, '');
    if (numbers.length <= 3) return numbers;
    if (numbers.length <= 6) return `(${numbers.slice(0, 3)}) ${numbers.slice(3)}`;
    return `(${numbers.slice(0, 3)}) ${numbers.slice(3, 6)}-${numbers.slice(6, 10)}`;
}

// Email domain extraction
function getEmailDomain(email: string): string | null {
    const match = email.match(/@([^@]+)$/);
    return match ? match[1] : null;
}

export function ContactFormDialog({
    open,
    onOpenChange,
    contact,
    onSubmit,
    isSubmitting,
}: ContactFormDialogProps) {
    const isEditing = !!contact;
    const [activeTab, setActiveTab] = useState('basic');
    const [showAdvanced, setShowAdvanced] = useState(false);

    const form = useForm<ContactFormValues>({
        resolver: zodResolver(contactFormSchema),
        defaultValues: {
            first_name: '',
            last_name: '',
            email: '',
            phone: '',
            company: '',
            job_title: '',
            source: '',
            status: 'lead',
            website: '',
            linkedin: '',
            address: '',
            notes: '',
        },
    });

    // Watch form values for real-time features
    const watchedEmail = useWatch({ control: form.control, name: 'email' });
    const watchedFirstName = useWatch({ control: form.control, name: 'first_name' });
    const watchedLastName = useWatch({ control: form.control, name: 'last_name' });
    const watchedCompany = useWatch({ control: form.control, name: 'company' });
    const watchedStatus = useWatch({ control: form.control, name: 'status' });

    // Auto-suggest company website from email domain
    const suggestedWebsite = useMemo(() => {
        const domain = getEmailDomain(watchedEmail || '');
        if (domain && !domain.includes('gmail') && !domain.includes('yahoo') && !domain.includes('hotmail') && !domain.includes('outlook')) {
            return `https://${domain}`;
        }
        return null;
    }, [watchedEmail]);

    // Generate initials for avatar preview
    const initials = useMemo(() => {
        const first = watchedFirstName?.[0] || '';
        const last = watchedLastName?.[0] || '';
        return (first + last).toUpperCase() || '?';
    }, [watchedFirstName, watchedLastName]);

    // Form completion percentage
    const completionPercentage = useMemo(() => {
        const values = form.getValues();
        const fields = [
            values.first_name,
            values.last_name,
            values.email,
            values.phone,
            values.company,
            values.job_title,
            values.source,
        ];
        const filled = fields.filter((f) => f && f.trim().length > 0).length;
        return Math.round((filled / fields.length) * 100);
    }, [form, watchedFirstName, watchedLastName, watchedEmail, watchedCompany]);

    // Reset form when contact changes
    useEffect(() => {
        if (open) {
            if (contact) {
                form.reset({
                    first_name: contact.first_name,
                    last_name: contact.last_name,
                    email: contact.email,
                    phone: contact.phone ?? '',
                    company: contact.company ?? '',
                    job_title: (contact as any).job_title ?? '',
                    source: contact.source ?? '',
                    status: contact.status,
                    website: (contact as any).website ?? '',
                    linkedin: (contact as any).linkedin ?? '',
                    address: (contact as any).address ?? '',
                    notes: '',
                });
                // Show advanced if there's data there
                if ((contact as any).website || (contact as any).linkedin || (contact as any).address) {
                    setShowAdvanced(true);
                }
            } else {
                form.reset({
                    first_name: '',
                    last_name: '',
                    email: '',
                    phone: '',
                    company: '',
                    job_title: '',
                    source: '',
                    status: 'lead',
                    website: '',
                    linkedin: '',
                    address: '',
                    notes: '',
                });
                setShowAdvanced(false);
            }
            setActiveTab('basic');
        }
    }, [contact, form, open]);

    const handleSubmit = async (values: ContactFormValues) => {
        const data = {
            first_name: values.first_name.trim(),
            last_name: values.last_name.trim(),
            email: values.email.trim().toLowerCase(),
            phone: values.phone?.trim() || null,
            company: values.company?.trim() || null,
            source: values.source?.trim() || null,
            status: values.status as ContactStatus,
            // These would need to be added to your schema
            // job_title: values.job_title?.trim() || null,
            // website: values.website?.trim() || null,
            // linkedin: values.linkedin?.trim() || null,
            // address: values.address?.trim() || null,
        };

        try {
            if (isEditing && contact) {
                await onSubmit({ id: contact.id, ...data });
            } else {
                await onSubmit(data as ContactInsert);
            }
            onOpenChange(false);
        } catch (error) {
            // Error handled in parent
        }
    };

    const handleApplyWebsiteSuggestion = () => {
        if (suggestedWebsite) {
            form.setValue('website', suggestedWebsite);
            toast.success('Website applied from email domain');
        }
    };

    const copyEmail = () => {
        if (watchedEmail) {
            navigator.clipboard.writeText(watchedEmail);
            toast.success('Email copied');
        }
    };

    const currentStatus = statusConfig[watchedStatus || 'lead'];

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[600px] p-0 gap-0 overflow-hidden max-h-[90vh]">
                {/* Header */}
                <DialogHeader className="p-6 pb-4">
                    <div className="flex items-start gap-4">
                        {/* Avatar Preview */}
                        <div className="relative">
                            <div className="h-14 w-14 rounded-xl bg-gradient-to-br from-primary/80 to-primary flex items-center justify-center text-primary-foreground font-semibold text-lg shadow-lg">
                                {initials}
                            </div>
                            {isEditing && (
                                <div className="absolute -bottom-1 -right-1 h-5 w-5 rounded-full bg-green-500 border-2 border-background flex items-center justify-center">
                                    <CheckCircle2 className="h-3 w-3 text-white" />
                                </div>
                            )}
                        </div>

                        <div className="flex-1 min-w-0">
                            <DialogTitle className="text-lg">
                                {isEditing ? 'Edit Contact' : 'Add New Contact'}
                            </DialogTitle>
                            <DialogDescription className="mt-1">
                                {isEditing ? (
                                    <span className="flex items-center gap-2">
                                        Editing {contact?.first_name} {contact?.last_name}
                                        {contact?.email && (
                                            <Badge variant="secondary" className="text-xs">
                                                {contact.email}
                                            </Badge>
                                        )}
                                    </span>
                                ) : (
                                    'Fill in the details to create a new contact'
                                )}
                            </DialogDescription>

                            {/* Completion indicator */}
                            {!isEditing && (
                                <div className="flex items-center gap-2 mt-2">
                                    <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
                                        <div
                                            className="h-full bg-primary transition-all duration-300"
                                            style={{ width: `${completionPercentage}%` }}
                                        />
                                    </div>
                                    <span className="text-xs text-muted-foreground">
                                        {completionPercentage}% complete
                                    </span>
                                </div>
                            )}
                        </div>
                    </div>
                </DialogHeader>

                <Separator />

                {/* Form Content */}
                <ScrollArea className="max-h-[60vh]">
                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(handleSubmit)} className="p-6 space-y-6">
                            {/* Basic Information */}
                            <div className="space-y-4">
                                <div className="flex items-center gap-2">
                                    <User className="h-4 w-4 text-muted-foreground" />
                                    <h3 className="text-sm font-medium">Basic Information</h3>
                                </div>

                                {/* Name Fields */}
                                <div className="grid grid-cols-2 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="first_name"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">
                                                    First Name <span className="text-destructive">*</span>
                                                </FormLabel>
                                                <FormControl>
                                                    <Input
                                                        placeholder="John"
                                                        className="h-9"
                                                        {...field}
                                                        autoFocus
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="last_name"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">
                                                    Last Name <span className="text-destructive">*</span>
                                                </FormLabel>
                                                <FormControl>
                                                    <Input placeholder="Doe" className="h-9" {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>

                                {/* Email Field */}
                                <FormField
                                    control={form.control}
                                    name="email"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel className="text-xs">
                                                Email <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <FormControl>
                                                <div className="relative">
                                                    <Mail className="h-4 w-4 text-muted-foreground absolute left-3 top-1/2 -translate-y-1/2" />
                                                    <Input
                                                        type="email"
                                                        placeholder="john@company.com"
                                                        className="h-9 pl-9 pr-9"
                                                        {...field}
                                                    />
                                                    {field.value && (
                                                        <Button
                                                            type="button"
                                                            variant="ghost"
                                                            size="sm"
                                                            className="h-6 w-6 p-0 absolute right-2 top-1/2 -translate-y-1/2"
                                                            onClick={copyEmail}
                                                        >
                                                            <Copy className="h-3.5 w-3.5" />
                                                        </Button>
                                                    )}
                                                </div>
                                            </FormControl>
                                            {suggestedWebsite && !form.getValues('website') && (
                                                <div className="flex items-center gap-2 mt-1">
                                                    <Sparkles className="h-3 w-3 text-amber-500" />
                                                    <span className="text-xs text-muted-foreground">
                                                        Company detected:
                                                    </span>
                                                    <Button
                                                        type="button"
                                                        variant="link"
                                                        size="sm"
                                                        className="h-auto p-0 text-xs"
                                                        onClick={handleApplyWebsiteSuggestion}
                                                    >
                                                        {suggestedWebsite}
                                                    </Button>
                                                </div>
                                            )}
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* Phone Field */}
                                <FormField
                                    control={form.control}
                                    name="phone"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel className="text-xs">Phone</FormLabel>
                                            <FormControl>
                                                <div className="relative">
                                                    <Phone className="h-4 w-4 text-muted-foreground absolute left-3 top-1/2 -translate-y-1/2" />
                                                    <Input
                                                        placeholder="(555) 123-4567"
                                                        className="h-9 pl-9"
                                                        {...field}
                                                        onChange={(e) => {
                                                            const formatted = formatPhoneInput(e.target.value);
                                                            field.onChange(formatted);
                                                        }}
                                                    />
                                                </div>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <Separator />

                            {/* Company Information */}
                            <div className="space-y-4">
                                <div className="flex items-center gap-2">
                                    <Building2 className="h-4 w-4 text-muted-foreground" />
                                    <h3 className="text-sm font-medium">Company Information</h3>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="company"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">Company</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        placeholder="Acme Inc"
                                                        className="h-9"
                                                        {...field}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="job_title"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">Job Title</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        placeholder="Marketing Manager"
                                                        className="h-9"
                                                        {...field}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                            </div>

                            <Separator />

                            {/* Source & Status */}
                            <div className="space-y-4">
                                <div className="flex items-center gap-2">
                                    <Tag className="h-4 w-4 text-muted-foreground" />
                                    <h3 className="text-sm font-medium">Classification</h3>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    {/* Source Field with Suggestions */}
                                    <FormField
                                        control={form.control}
                                        name="source"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">Source</FormLabel>
                                                <Popover>
                                                    <PopoverTrigger asChild>
                                                        <FormControl>
                                                            <div className="relative">
                                                                <Input
                                                                    placeholder="How did they find you?"
                                                                    className="h-9 pr-8"
                                                                    {...field}
                                                                />
                                                                <ChevronDown className="h-4 w-4 text-muted-foreground absolute right-2.5 top-1/2 -translate-y-1/2" />
                                                            </div>
                                                        </FormControl>
                                                    </PopoverTrigger>
                                                    <PopoverContent className="w-[200px] p-1" align="start">
                                                        <div className="space-y-0.5">
                                                            {sourceSuggestions.map((source) => (
                                                                <Button
                                                                    key={source}
                                                                    type="button"
                                                                    variant="ghost"
                                                                    size="sm"
                                                                    className="w-full justify-start h-8 text-sm"
                                                                    onClick={() => {
                                                                        field.onChange(source);
                                                                    }}
                                                                >
                                                                    {source}
                                                                </Button>
                                                            ))}
                                                        </div>
                                                    </PopoverContent>
                                                </Popover>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Status Field - Visual Cards */}
                                    <FormField
                                        control={form.control}
                                        name="status"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">Status</FormLabel>
                                                <Select onValueChange={field.onChange} value={field.value}>
                                                    <FormControl>
                                                        <SelectTrigger className="h-9">
                                                            <SelectValue>
                                                                <div className="flex items-center gap-2">
                                                                    <div className={cn("p-1 rounded", currentStatus.bg)}>
                                                                        <currentStatus.icon className={cn("h-3 w-3", currentStatus.color)} />
                                                                    </div>
                                                                    <span>{currentStatus.label}</span>
                                                                </div>
                                                            </SelectValue>
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        {Object.entries(statusConfig).map(([value, config]) => (
                                                            <SelectItem key={value} value={value}>
                                                                <div className="flex items-center gap-2">
                                                                    <div className={cn("p-1 rounded", config.bg)}>
                                                                        <config.icon className={cn("h-3.5 w-3.5", config.color)} />
                                                                    </div>
                                                                    <div>
                                                                        <span className="font-medium">{config.label}</span>
                                                                        <span className="text-xs text-muted-foreground ml-2">
                                                                            {config.description}
                                                                        </span>
                                                                    </div>
                                                                </div>
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                            </div>

                            {/* Advanced Fields - Collapsible */}
                            <Collapsible open={showAdvanced} onOpenChange={setShowAdvanced}>
                                <CollapsibleTrigger asChild>
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="sm"
                                        className="w-full justify-between h-9 px-3"
                                    >
                                        <span className="flex items-center gap-2 text-sm">
                                            <Sparkles className="h-4 w-4" />
                                            Additional Details
                                        </span>
                                        <ChevronDown
                                            className={cn(
                                                "h-4 w-4 transition-transform",
                                                showAdvanced && "rotate-180"
                                            )}
                                        />
                                    </Button>
                                </CollapsibleTrigger>
                                <CollapsibleContent className="space-y-4 pt-4">
                                    {/* Website */}
                                    <FormField
                                        control={form.control}
                                        name="website"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">Website</FormLabel>
                                                <FormControl>
                                                    <div className="relative">
                                                        <Globe className="h-4 w-4 text-muted-foreground absolute left-3 top-1/2 -translate-y-1/2" />
                                                        <Input
                                                            placeholder="https://company.com"
                                                            className="h-9 pl-9 pr-9"
                                                            {...field}
                                                        />
                                                        {field.value && (
                                                            <Button
                                                                type="button"
                                                                variant="ghost"
                                                                size="sm"
                                                                className="h-6 w-6 p-0 absolute right-2 top-1/2 -translate-y-1/2"
                                                                onClick={() => window.open(field.value, '_blank')}
                                                            >
                                                                <ExternalLink className="h-3.5 w-3.5" />
                                                            </Button>
                                                        )}
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* LinkedIn */}
                                    <FormField
                                        control={form.control}
                                        name="linkedin"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">LinkedIn</FormLabel>
                                                <FormControl>
                                                    <div className="relative">
                                                        <Link2 className="h-4 w-4 text-muted-foreground absolute left-3 top-1/2 -translate-y-1/2" />
                                                        <Input
                                                            placeholder="linkedin.com/in/username"
                                                            className="h-9 pl-9"
                                                            {...field}
                                                        />
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Address */}
                                    <FormField
                                        control={form.control}
                                        name="address"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">Address</FormLabel>
                                                <FormControl>
                                                    <div className="relative">
                                                        <MapPin className="h-4 w-4 text-muted-foreground absolute left-3 top-3" />
                                                        <Textarea
                                                            placeholder="123 Main St, City, State ZIP"
                                                            className="pl-9 min-h-[60px] resize-none"
                                                            {...field}
                                                        />
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Initial Notes */}
                                    <FormField
                                        control={form.control}
                                        name="notes"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="text-xs">Initial Notes</FormLabel>
                                                <FormControl>
                                                    <Textarea
                                                        placeholder="Add any initial notes about this contact..."
                                                        className="min-h-[80px] resize-none"
                                                        {...field}
                                                    />
                                                </FormControl>
                                                <FormDescription className="text-xs">
                                                    This will be saved as the first note for this contact
                                                </FormDescription>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </CollapsibleContent>
                            </Collapsible>
                        </form>
                    </Form>
                </ScrollArea>

                <Separator />

                {/* Footer */}
                <div className="p-4 bg-muted/30">
                    <div className="flex items-center justify-between">
                        {/* Tips */}
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                            <Info className="h-3.5 w-3.5" />
                            <span>
                                {isEditing
                                    ? 'Changes are saved immediately'
                                    : 'Required fields are marked with *'}
                            </span>
                        </div>

                        {/* Actions */}
                        <div className="flex items-center gap-2">
                            <Button
                                type="button"
                                variant="ghost"
                                onClick={() => onOpenChange(false)}
                                disabled={isSubmitting}
                            >
                                Cancel
                            </Button>
                            <Button
                                onClick={form.handleSubmit(handleSubmit)}
                                disabled={isSubmitting}
                                className="min-w-[100px]"
                            >
                                {isSubmitting ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        Saving...
                                    </>
                                ) : isEditing ? (
                                    <>
                                        <Save className="mr-2 h-4 w-4" />
                                        Save
                                    </>
                                ) : (
                                    <>
                                        <UserPlus className="mr-2 h-4 w-4" />
                                        Add Contact
                                    </>
                                )}
                            </Button>
                        </div>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
}