import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
    Building2,
    Save,
    Loader2,
    Plus,
    X,
    Upload,
    Trash2,
    Mail,
    Eye,
    EyeOff,
    TestTube,
    CheckCircle,
    XCircle,
    Palette,
    Sun,
    Moon,
    Monitor,
    Sidebar,
    PanelTop,
    Settings,
} from 'lucide-react';
import { useBusiness, useBusinessEmailConfig } from '@/hooks/useBusiness';
import { useBusinessLogo } from '@/hooks/useBusinessLogo';
import { useTheme } from '@/contexts/ThemeContext';
import { supabase } from '@/integrations/supabase/client';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Switch } from '@/components/ui/switch';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { toast } from 'sonner';

// Constants
const themeOptions = [
    { value: 'system', label: 'System', icon: Monitor },
    { value: 'light', label: 'Light', icon: Sun },
    { value: 'dark', label: 'Dark', icon: Moon },
];

const layoutOptions = [
    { value: 'sidebar', label: 'Sidebar', icon: Sidebar },
    { value: 'topbar', label: 'Topbar', icon: PanelTop },
];

const accentColors = [
    { value: 'blue', label: 'Blue', color: '#3B82F6' },
    { value: 'purple', label: 'Purple', color: '#8B5CF6' },
    { value: 'green', label: 'Green', color: '#10B981' },
    { value: 'orange', label: 'Orange', color: '#F59E0B' },
    { value: 'pink', label: 'Pink', color: '#EC4899' },
    { value: 'teal', label: 'Teal', color: '#14B8A6' },
];

const encryptionOptions = [
    { value: 'tls', label: 'TLS (Recommended)' },
    { value: 'ssl', label: 'SSL' },
    { value: 'none', label: 'None' },
];

const tabs = [
    { id: 'business', label: 'Business', icon: Building2 },
    { id: 'appearance', label: 'Appearance', icon: Palette },
    { id: 'email', label: 'Email', icon: Mail },
];

// Animation variants
const tabContentVariants = {
    hidden: { opacity: 0, y: 10 },
    visible: { opacity: 1, y: 0, transition: { duration: 0.3, ease: 'easeOut' } },
    exit: { opacity: 0, y: -10, transition: { duration: 0.2 } },
};

const sectionVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: (i: number) => ({
        opacity: 1,
        y: 0,
        transition: { delay: i * 0.1, duration: 0.3 },
    }),
};

export default function SettingsPage() {
    const [activeTab, setActiveTab] = useState('business');

    const { business, isLoading: isLoadingBusiness, createBusiness, updateBusiness, isCreating, isUpdating } = useBusiness();
    const { uploadLogo, deleteLogo, isUploading } = useBusinessLogo();
    const { emailConfig, isLoading: isLoadingConfig, saveEmailConfig, isSaving } = useBusinessEmailConfig(business?.id);
    const { theme, setTheme } = useTheme();
    const fileInputRef = useRef<HTMLInputElement>(null);

    // Business form state
    const [businessForm, setBusinessForm] = useState({
        name: '',
        location: '',
        address: '',
        city: '',
        state: '',
        postal_code: '',
        country: '',
        industries: [] as string[],
        phone: '',
        email: '',
        website: '',
        owner_name: '',
        owner_email: '',
        owner_phone: '',
        preferred_theme: 'system',
        preferred_accent_color: 'blue',
        preferred_layout: 'sidebar',
        logo_url: null as string | null,
    });

    const [newIndustry, setNewIndustry] = useState('');

    // Email form state
    const [emailForm, setEmailForm] = useState({
        smtp_host: '',
        smtp_port: 587,
        smtp_username: '',
        smtp_password: '',
        smtp_encryption: 'tls',
        from_email: '',
        from_name: '',
        reply_to_email: '',
        is_active: false,
    });

    const [showPassword, setShowPassword] = useState(false);
    const [isTesting, setIsTesting] = useState(false);

    // Load business data
    useEffect(() => {
        if (business) {
            setBusinessForm({
                name: business.name || '',
                location: business.location || '',
                address: business.address || '',
                city: business.city || '',
                state: business.state || '',
                postal_code: business.postal_code || '',
                country: business.country || '',
                industries: business.industries || [],
                phone: business.phone || '',
                email: business.email || '',
                website: business.website || '',
                owner_name: business.owner_name || '',
                owner_email: business.owner_email || '',
                owner_phone: business.owner_phone || '',
                preferred_theme: business.preferred_theme || 'system',
                preferred_accent_color: business.preferred_accent_color || 'blue',
                preferred_layout: business.preferred_layout || 'sidebar',
                logo_url: business.logo_url || null,
            });
        }
    }, [business]);

    // Load email config
    useEffect(() => {
        if (emailConfig) {
            setEmailForm({
                smtp_host: emailConfig.smtp_host || '',
                smtp_port: emailConfig.smtp_port || 587,
                smtp_username: emailConfig.smtp_username || '',
                smtp_password: emailConfig.smtp_password || '',
                smtp_encryption: emailConfig.smtp_encryption || 'tls',
                from_email: emailConfig.from_email || '',
                from_name: emailConfig.from_name || '',
                reply_to_email: emailConfig.reply_to_email || '',
                is_active: emailConfig.is_active || false,
            });
        }
    }, [emailConfig]);

    // Business handlers
    const handleBusinessSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            if (business) {
                await updateBusiness({ id: business.id, ...businessForm });
            } else {
                await createBusiness(businessForm);
            }
        } catch (error) {
            // Error handled in hook
        }
    };

    const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file || !business) return;

        try {
            const logoUrl = await uploadLogo(business.id, file, businessForm.logo_url);
            setBusinessForm(prev => ({ ...prev, logo_url: logoUrl }));
        } catch (error) {
            // Error handled in hook
        }
    };

    const handleLogoDelete = async () => {
        if (!business || !businessForm.logo_url) return;

        try {
            await deleteLogo(business.id, businessForm.logo_url);
            setBusinessForm(prev => ({ ...prev, logo_url: null }));
        } catch (error) {
            // Error handled in hook
        }
    };

    const addIndustry = () => {
        if (newIndustry.trim() && !businessForm.industries.includes(newIndustry.trim())) {
            setBusinessForm(prev => ({
                ...prev,
                industries: [...prev.industries, newIndustry.trim()],
            }));
            setNewIndustry('');
        }
    };

    const removeIndustry = (industry: string) => {
        setBusinessForm(prev => ({
            ...prev,
            industries: prev.industries.filter(i => i !== industry),
        }));
    };

    // Theme handlers
    const handleThemeChange = (value: string) => {
        setBusinessForm(prev => ({ ...prev, preferred_theme: value }));
        setTheme({ mode: value as 'light' | 'dark' | 'system' });
    };

    const handleLayoutChange = (value: string) => {
        setBusinessForm(prev => ({ ...prev, preferred_layout: value }));
        setTheme({ layoutMode: value as 'sidebar' | 'topbar' });
    };

    const handleAccentColorChange = (value: string) => {
        setBusinessForm(prev => ({ ...prev, preferred_accent_color: value }));
        setTheme({ accentColor: value });
    };

    // Email handlers
    const handleEmailSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!business?.id) {
            toast.error('Please create a business first');
            return;
        }
        try {
            await saveEmailConfig({
                business_id: business.id,
                provider: 'smtp',
                ...emailForm,
            });
        } catch (error) {
            // Error handled in hook
        }
    };

    const handleTestConnection = async () => {
        if (!business?.id) {
            toast.error('Please create a business first');
            return;
        }

        if (!emailForm.smtp_host || !emailForm.smtp_username || !emailForm.smtp_password) {
            toast.error('Please fill in all SMTP fields before testing');
            return;
        }

        setIsTesting(true);
        try {
            const { data: { session } } = await supabase.auth.getSession();
            if (!session) {
                toast.error('Please log in to test the connection');
                return;
            }

            const response = await supabase.functions.invoke('test-smtp', {
                body: { business_id: business.id },
            });

            if (response.error) {
                throw new Error(response.error.message);
            }

            if (response.data.success) {
                toast.success(response.data.message, {
                    icon: <CheckCircle className="h-4 w-4 text-green-500" />,
                });
            } else {
                toast.error(response.data.error || 'Test failed', {
                    icon: <XCircle className="h-4 w-4 text-destructive" />,
                });
            }
        } catch (error: any) {
            toast.error(error.message || 'Failed to test SMTP connection');
        } finally {
            setIsTesting(false);
        }
    };

    const isLoading = isLoadingBusiness || isLoadingConfig;

    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-[calc(100vh-200px)]">
                <div className="flex flex-col items-center gap-4">
                    <Loader2 className="h-10 w-10 animate-spin text-primary" />
                    <p className="text-muted-foreground">Loading settings...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted/20">
            <div className="container max-w-5xl py-8 px-4 sm:px-6 lg:px-8">
                {/* Header */}
                <motion.div
                    initial={{ opacity: 0, y: -20 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="mb-8"
                >
                    <div className="flex items-center gap-3 mb-2">
                        <div className="p-2 rounded-xl bg-primary/10">
                            <Settings className="h-6 w-6 text-primary" />
                        </div>
                        <h1 className="text-3xl font-bold tracking-tight">Settings</h1>
                    </div>
                    <p className="text-muted-foreground ml-12">
                        Manage your business, appearance, and email configuration
                    </p>
                </motion.div>

                {/* Tabs */}
                <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-8">
                    <motion.div
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.1 }}
                    >
                        <TabsList className="grid w-full grid-cols-3 h-14 p-1 bg-muted/50 backdrop-blur-sm rounded-2xl">
                            {tabs.map((tab) => (
                                <TabsTrigger
                                    key={tab.id}
                                    value={tab.id}
                                    className={cn(
                                        'flex items-center gap-2 rounded-xl transition-all duration-300 data-[state=active]:bg-background data-[state=active]:shadow-lg',
                                        'hover:bg-background/50'
                                    )}
                                >
                                    <tab.icon className="h-4 w-4" />
                                    <span className="hidden sm:inline">{tab.label}</span>
                                </TabsTrigger>
                            ))}
                        </TabsList>
                    </motion.div>

                    {/* Business Tab */}
                    <AnimatePresence mode="wait">
                        <TabsContent value="business" className="mt-8">
                            <motion.div
                                key="business"
                                variants={tabContentVariants}
                                initial="hidden"
                                animate="visible"
                                exit="exit"
                            >
                                <Card className="border-0 shadow-xl bg-card/50 backdrop-blur-sm">
                                    <CardHeader className="pb-4">
                                        <CardTitle className="flex items-center gap-2">
                                            <Building2 className="h-5 w-5 text-primary" />
                                            Business Information
                                        </CardTitle>
                                        <CardDescription>
                                            Configure your business details. These values can be used in email and SMS templates.
                                        </CardDescription>
                                    </CardHeader>
                                    <CardContent>
                                        <form onSubmit={handleBusinessSubmit} className="space-y-8">
                                            {/* Logo Upload */}
                                            <motion.div
                                                custom={0}
                                                variants={sectionVariants}
                                                initial="hidden"
                                                animate="visible"
                                                className="flex items-center gap-6 p-4 rounded-xl bg-muted/30"
                                            >
                                                <Avatar className="h-24 w-24 ring-4 ring-background shadow-lg">
                                                    <AvatarImage src={businessForm.logo_url || undefined} alt="Business logo" />
                                                    <AvatarFallback className="text-2xl bg-primary/10 text-primary">
                                                        {businessForm.name ? businessForm.name.charAt(0).toUpperCase() : 'B'}
                                                    </AvatarFallback>
                                                </Avatar>
                                                <div className="flex flex-col gap-2">
                                                    <input
                                                        ref={fileInputRef}
                                                        type="file"
                                                        accept="image/*"
                                                        onChange={handleLogoUpload}
                                                        className="hidden"
                                                    />
                                                    <Button
                                                        type="button"
                                                        variant="outline"
                                                        size="sm"
                                                        onClick={() => fileInputRef.current?.click()}
                                                        disabled={isUploading || !business}
                                                        className="gap-2"
                                                    >
                                                        {isUploading ? (
                                                            <Loader2 className="h-4 w-4 animate-spin" />
                                                        ) : (
                                                            <Upload className="h-4 w-4" />
                                                        )}
                                                        Upload Logo
                                                    </Button>
                                                    {businessForm.logo_url && (
                                                        <Button
                                                            type="button"
                                                            variant="ghost"
                                                            size="sm"
                                                            onClick={handleLogoDelete}
                                                            className="text-destructive hover:text-destructive gap-2"
                                                        >
                                                            <Trash2 className="h-4 w-4" />
                                                            Remove
                                                        </Button>
                                                    )}
                                                    {!business && (
                                                        <p className="text-xs text-muted-foreground">Save business first to upload logo</p>
                                                    )}
                                                </div>
                                            </motion.div>

                                            {/* Basic Info */}
                                            <motion.div
                                                custom={1}
                                                variants={sectionVariants}
                                                initial="hidden"
                                                animate="visible"
                                                className="space-y-4"
                                            >
                                                <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                    Basic Information
                                                </h3>
                                                <div className="grid gap-4 sm:grid-cols-2">
                                                    <div className="space-y-2">
                                                        <Label htmlFor="name">Business Name *</Label>
                                                        <Input
                                                            id="name"
                                                            value={businessForm.name}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, name: e.target.value }))}
                                                            placeholder="Acme Inc."
                                                            required
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="website">Website</Label>
                                                        <Input
                                                            id="website"
                                                            value={businessForm.website}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, website: e.target.value }))}
                                                            placeholder="https://example.com"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="phone">Phone</Label>
                                                        <Input
                                                            id="phone"
                                                            value={businessForm.phone}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, phone: e.target.value }))}
                                                            placeholder="+1 (555) 000-0000"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="email">Email</Label>
                                                        <Input
                                                            id="email"
                                                            type="email"
                                                            value={businessForm.email}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, email: e.target.value }))}
                                                            placeholder="info@example.com"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                </div>

                                                {/* Industries */}
                                                <div className="space-y-2">
                                                    <Label>Industries</Label>
                                                    <div className="flex gap-2">
                                                        <Input
                                                            value={newIndustry}
                                                            onChange={(e) => setNewIndustry(e.target.value)}
                                                            placeholder="Add industry..."
                                                            onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addIndustry())}
                                                            className="bg-background"
                                                        />
                                                        <Button type="button" variant="outline" onClick={addIndustry} size="icon">
                                                            <Plus className="h-4 w-4" />
                                                        </Button>
                                                    </div>
                                                    {businessForm.industries.length > 0 && (
                                                        <div className="flex flex-wrap gap-2 mt-2">
                                                            {businessForm.industries.map((industry) => (
                                                                <Badge key={industry} variant="secondary" className="gap-1 px-3 py-1">
                                                                    {industry}
                                                                    <button type="button" onClick={() => removeIndustry(industry)}>
                                                                        <X className="h-3 w-3" />
                                                                    </button>
                                                                </Badge>
                                                            ))}
                                                        </div>
                                                    )}
                                                </div>
                                            </motion.div>

                                            <Separator />

                                            {/* Address */}
                                            <motion.div
                                                custom={2}
                                                variants={sectionVariants}
                                                initial="hidden"
                                                animate="visible"
                                                className="space-y-4"
                                            >
                                                <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                    Location & Address
                                                </h3>
                                                <div className="grid gap-4 sm:grid-cols-2">
                                                    <div className="space-y-2 sm:col-span-2">
                                                        <Label htmlFor="address">Address</Label>
                                                        <Input
                                                            id="address"
                                                            value={businessForm.address}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, address: e.target.value }))}
                                                            placeholder="123 Main Street"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="city">City</Label>
                                                        <Input
                                                            id="city"
                                                            value={businessForm.city}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, city: e.target.value }))}
                                                            placeholder="New York"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="state">State</Label>
                                                        <Input
                                                            id="state"
                                                            value={businessForm.state}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, state: e.target.value }))}
                                                            placeholder="NY"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="postal_code">Postal Code</Label>
                                                        <Input
                                                            id="postal_code"
                                                            value={businessForm.postal_code}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, postal_code: e.target.value }))}
                                                            placeholder="10001"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="country">Country</Label>
                                                        <Input
                                                            id="country"
                                                            value={businessForm.country}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, country: e.target.value }))}
                                                            placeholder="United States"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                </div>
                                            </motion.div>

                                            <Separator />

                                            {/* Owner Info */}
                                            <motion.div
                                                custom={3}
                                                variants={sectionVariants}
                                                initial="hidden"
                                                animate="visible"
                                                className="space-y-4"
                                            >
                                                <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                    Owner Information
                                                </h3>
                                                <div className="grid gap-4 sm:grid-cols-2">
                                                    <div className="space-y-2">
                                                        <Label htmlFor="owner_name">Owner Name</Label>
                                                        <Input
                                                            id="owner_name"
                                                            value={businessForm.owner_name}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, owner_name: e.target.value }))}
                                                            placeholder="John Doe"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="owner_email">Owner Email</Label>
                                                        <Input
                                                            id="owner_email"
                                                            type="email"
                                                            value={businessForm.owner_email}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, owner_email: e.target.value }))}
                                                            placeholder="john@example.com"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="owner_phone">Owner Phone</Label>
                                                        <Input
                                                            id="owner_phone"
                                                            value={businessForm.owner_phone}
                                                            onChange={(e) => setBusinessForm(prev => ({ ...prev, owner_phone: e.target.value }))}
                                                            placeholder="+1 (555) 000-0000"
                                                            className="bg-background"
                                                        />
                                                    </div>
                                                </div>
                                            </motion.div>

                                            <div className="flex justify-end pt-4">
                                                <Button
                                                    type="submit"
                                                    disabled={isCreating || isUpdating || !businessForm.name.trim()}
                                                    className="gap-2"
                                                >
                                                    {(isCreating || isUpdating) && <Loader2 className="h-4 w-4 animate-spin" />}
                                                    <Save className="h-4 w-4" />
                                                    {business ? 'Save Changes' : 'Create Business'}
                                                </Button>
                                            </div>
                                        </form>
                                    </CardContent>
                                </Card>
                            </motion.div>
                        </TabsContent>
                    </AnimatePresence>

                    {/* Appearance Tab */}
                    <AnimatePresence mode="wait">
                        <TabsContent value="appearance" className="mt-8">
                            <motion.div
                                key="appearance"
                                variants={tabContentVariants}
                                initial="hidden"
                                animate="visible"
                                exit="exit"
                            >
                                <Card className="border-0 shadow-xl bg-card/50 backdrop-blur-sm">
                                    <CardHeader className="pb-4">
                                        <CardTitle className="flex items-center gap-2">
                                            <Palette className="h-5 w-5 text-primary" />
                                            Appearance
                                        </CardTitle>
                                        <CardDescription>
                                            Customize the look and feel of your CRM
                                        </CardDescription>
                                    </CardHeader>
                                    <CardContent className="space-y-8">
                                        {/* Theme Mode */}
                                        <motion.div
                                            custom={0}
                                            variants={sectionVariants}
                                            initial="hidden"
                                            animate="visible"
                                            className="space-y-4"
                                        >
                                            <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                Theme Mode
                                            </h3>
                                            <div className="grid grid-cols-3 gap-4">
                                                {themeOptions.map(({ value, label, icon: Icon }) => (
                                                    <button
                                                        key={value}
                                                        type="button"
                                                        onClick={() => handleThemeChange(value)}
                                                        className={cn(
                                                            'flex flex-col items-center gap-3 rounded-xl border-2 p-6 transition-all duration-200',
                                                            theme.mode === value
                                                                ? 'border-primary bg-primary/5 shadow-lg scale-[1.02]'
                                                                : 'border-border hover:border-primary/50 hover:bg-muted/50'
                                                        )}
                                                    >
                                                        <div className={cn(
                                                            'p-3 rounded-full transition-colors',
                                                            theme.mode === value ? 'bg-primary/10' : 'bg-muted'
                                                        )}>
                                                            <Icon className={cn(
                                                                'h-6 w-6',
                                                                theme.mode === value ? 'text-primary' : 'text-muted-foreground'
                                                            )} />
                                                        </div>
                                                        <span className={cn(
                                                            'text-sm font-medium',
                                                            theme.mode === value ? 'text-primary' : 'text-muted-foreground'
                                                        )}>
                                                            {label}
                                                        </span>
                                                    </button>
                                                ))}
                                            </div>
                                        </motion.div>

                                        <Separator />

                                        {/* Layout Mode */}
                                        <motion.div
                                            custom={1}
                                            variants={sectionVariants}
                                            initial="hidden"
                                            animate="visible"
                                            className="space-y-4"
                                        >
                                            <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                Navigation Layout
                                            </h3>
                                            <div className="grid grid-cols-2 gap-4">
                                                {layoutOptions.map(({ value, label, icon: Icon }) => (
                                                    <button
                                                        key={value}
                                                        type="button"
                                                        onClick={() => handleLayoutChange(value)}
                                                        className={cn(
                                                            'flex flex-col items-center gap-3 rounded-xl border-2 p-6 transition-all duration-200',
                                                            theme.layoutMode === value
                                                                ? 'border-primary bg-primary/5 shadow-lg scale-[1.02]'
                                                                : 'border-border hover:border-primary/50 hover:bg-muted/50'
                                                        )}
                                                    >
                                                        <div className={cn(
                                                            'p-3 rounded-full transition-colors',
                                                            theme.layoutMode === value ? 'bg-primary/10' : 'bg-muted'
                                                        )}>
                                                            <Icon className={cn(
                                                                'h-6 w-6',
                                                                theme.layoutMode === value ? 'text-primary' : 'text-muted-foreground'
                                                            )} />
                                                        </div>
                                                        <span className={cn(
                                                            'text-sm font-medium',
                                                            theme.layoutMode === value ? 'text-primary' : 'text-muted-foreground'
                                                        )}>
                                                            {label}
                                                        </span>
                                                    </button>
                                                ))}
                                            </div>
                                        </motion.div>

                                        <Separator />

                                        {/* Accent Color */}
                                        <motion.div
                                            custom={2}
                                            variants={sectionVariants}
                                            initial="hidden"
                                            animate="visible"
                                            className="space-y-4"
                                        >
                                            <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                Accent Color
                                            </h3>
                                            <div className="flex gap-4 flex-wrap">
                                                {accentColors.map((accent) => (
                                                    <button
                                                        key={accent.value}
                                                        type="button"
                                                        onClick={() => handleAccentColorChange(accent.value)}
                                                        className={cn(
                                                            'h-12 w-12 rounded-full transition-all duration-200 shadow-lg',
                                                            theme.accentColor === accent.value
                                                                ? 'ring-4 ring-offset-4 ring-offset-background ring-foreground/20 scale-110'
                                                                : 'hover:scale-105'
                                                        )}
                                                        style={{ backgroundColor: accent.color }}
                                                        title={accent.label}
                                                    />
                                                ))}
                                            </div>
                                        </motion.div>

                                        <Separator />

                                        {/* Density */}
                                        <motion.div
                                            custom={3}
                                            variants={sectionVariants}
                                            initial="hidden"
                                            animate="visible"
                                            className="space-y-4"
                                        >
                                            <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                Density
                                            </h3>
                                            <RadioGroup
                                                value={theme.density}
                                                onValueChange={(value) => setTheme({ density: value as 'comfortable' | 'compact' })}
                                                className="flex gap-6"
                                            >
                                                <div className="flex items-center space-x-3">
                                                    <RadioGroupItem value="comfortable" id="comfortable" className="h-5 w-5" />
                                                    <Label htmlFor="comfortable" className="cursor-pointer text-base">
                                                        Comfortable
                                                    </Label>
                                                </div>
                                                <div className="flex items-center space-x-3">
                                                    <RadioGroupItem value="compact" id="compact" className="h-5 w-5" />
                                                    <Label htmlFor="compact" className="cursor-pointer text-base">
                                                        Compact
                                                    </Label>
                                                </div>
                                            </RadioGroup>
                                        </motion.div>
                                    </CardContent>
                                </Card>
                            </motion.div>
                        </TabsContent>
                    </AnimatePresence>

                    {/* Email Tab */}
                    <AnimatePresence mode="wait">
                        <TabsContent value="email" className="mt-8">
                            <motion.div
                                key="email"
                                variants={tabContentVariants}
                                initial="hidden"
                                animate="visible"
                                exit="exit"
                            >
                                {!business ? (
                                    <Card className="border-dashed border-2 shadow-xl bg-card/50 backdrop-blur-sm">
                                        <CardHeader className="text-center py-12">
                                            <div className="mx-auto p-4 rounded-full bg-muted mb-4">
                                                <Mail className="h-12 w-12 text-muted-foreground" />
                                            </div>
                                            <CardTitle>No Business Configured</CardTitle>
                                            <CardDescription className="max-w-sm mx-auto">
                                                Please create a business first before configuring email settings.
                                            </CardDescription>
                                        </CardHeader>
                                        <CardContent className="text-center pb-12">
                                            <Button onClick={() => setActiveTab('business')} className="gap-2">
                                                <Building2 className="h-4 w-4" />
                                                Configure Business
                                            </Button>
                                        </CardContent>
                                    </Card>
                                ) : (
                                    <Card className="border-0 shadow-xl bg-card/50 backdrop-blur-sm">
                                        <CardHeader className="pb-4">
                                            <CardTitle className="flex items-center gap-2">
                                                <Mail className="h-5 w-5 text-primary" />
                                                Email Configuration
                                            </CardTitle>
                                            <CardDescription>
                                                Configure SMTP settings for sending emails from your business
                                            </CardDescription>
                                        </CardHeader>
                                        <CardContent>
                                            <form onSubmit={handleEmailSubmit} className="space-y-8">
                                                {/* SMTP Server */}
                                                <motion.div
                                                    custom={0}
                                                    variants={sectionVariants}
                                                    initial="hidden"
                                                    animate="visible"
                                                    className="space-y-4"
                                                >
                                                    <div className="flex items-center justify-between">
                                                        <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                            SMTP Server
                                                        </h3>
                                                        <div className="flex items-center gap-3 p-2 rounded-lg bg-muted/50">
                                                            <Label htmlFor="is_active" className="text-sm">
                                                                Enable email sending
                                                            </Label>
                                                            <Switch
                                                                id="is_active"
                                                                checked={emailForm.is_active}
                                                                onCheckedChange={(checked) => setEmailForm(prev => ({ ...prev, is_active: checked }))}
                                                            />
                                                        </div>
                                                    </div>

                                                    <div className="grid gap-4 sm:grid-cols-2">
                                                        <div className="space-y-2">
                                                            <Label htmlFor="smtp_host">SMTP Host</Label>
                                                            <Input
                                                                id="smtp_host"
                                                                value={emailForm.smtp_host}
                                                                onChange={(e) => setEmailForm(prev => ({ ...prev, smtp_host: e.target.value }))}
                                                                placeholder="smtp.gmail.com"
                                                                className="bg-background"
                                                            />
                                                        </div>
                                                        <div className="space-y-2">
                                                            <Label htmlFor="smtp_port">SMTP Port</Label>
                                                            <Input
                                                                id="smtp_port"
                                                                type="number"
                                                                value={emailForm.smtp_port}
                                                                onChange={(e) => setEmailForm(prev => ({ ...prev, smtp_port: parseInt(e.target.value) || 587 }))}
                                                                placeholder="587"
                                                                className="bg-background"
                                                            />
                                                        </div>
                                                        <div className="space-y-2">
                                                            <Label htmlFor="smtp_username">Username</Label>
                                                            <Input
                                                                id="smtp_username"
                                                                value={emailForm.smtp_username}
                                                                onChange={(e) => setEmailForm(prev => ({ ...prev, smtp_username: e.target.value }))}
                                                                placeholder="your-email@gmail.com"
                                                                className="bg-background"
                                                            />
                                                        </div>
                                                        <div className="space-y-2">
                                                            <Label htmlFor="smtp_password">Password</Label>
                                                            <div className="relative">
                                                                <Input
                                                                    id="smtp_password"
                                                                    type={showPassword ? 'text' : 'password'}
                                                                    value={emailForm.smtp_password}
                                                                    onChange={(e) => setEmailForm(prev => ({ ...prev, smtp_password: e.target.value }))}
                                                                    placeholder="App password"
                                                                    className="pr-10 bg-background"
                                                                />
                                                                <button
                                                                    type="button"
                                                                    onClick={() => setShowPassword(!showPassword)}
                                                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                                                                >
                                                                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                                                </button>
                                                            </div>
                                                        </div>
                                                        <div className="space-y-2">
                                                            <Label>Encryption</Label>
                                                            <Select
                                                                value={emailForm.smtp_encryption}
                                                                onValueChange={(value) => setEmailForm(prev => ({ ...prev, smtp_encryption: value }))}
                                                            >
                                                                <SelectTrigger className="bg-background">
                                                                    <SelectValue />
                                                                </SelectTrigger>
                                                                <SelectContent>
                                                                    {encryptionOptions.map(opt => (
                                                                        <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                                                                    ))}
                                                                </SelectContent>
                                                            </Select>
                                                        </div>
                                                    </div>
                                                </motion.div>

                                                <Separator />

                                                {/* Sender Info */}
                                                <motion.div
                                                    custom={1}
                                                    variants={sectionVariants}
                                                    initial="hidden"
                                                    animate="visible"
                                                    className="space-y-4"
                                                >
                                                    <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                        Sender Information
                                                    </h3>
                                                    <div className="grid gap-4 sm:grid-cols-2">
                                                        <div className="space-y-2">
                                                            <Label htmlFor="from_name">From Name</Label>
                                                            <Input
                                                                id="from_name"
                                                                value={emailForm.from_name}
                                                                onChange={(e) => setEmailForm(prev => ({ ...prev, from_name: e.target.value }))}
                                                                placeholder="Your Business Name"
                                                                className="bg-background"
                                                            />
                                                        </div>
                                                        <div className="space-y-2">
                                                            <Label htmlFor="from_email">From Email</Label>
                                                            <Input
                                                                id="from_email"
                                                                type="email"
                                                                value={emailForm.from_email}
                                                                onChange={(e) => setEmailForm(prev => ({ ...prev, from_email: e.target.value }))}
                                                                placeholder="noreply@yourdomain.com"
                                                                className="bg-background"
                                                            />
                                                        </div>
                                                        <div className="space-y-2 sm:col-span-2">
                                                            <Label htmlFor="reply_to_email">Reply-To Email</Label>
                                                            <Input
                                                                id="reply_to_email"
                                                                type="email"
                                                                value={emailForm.reply_to_email}
                                                                onChange={(e) => setEmailForm(prev => ({ ...prev, reply_to_email: e.target.value }))}
                                                                placeholder="support@yourdomain.com"
                                                                className="bg-background"
                                                            />
                                                        </div>
                                                    </div>
                                                </motion.div>

                                                <Separator />

                                                {/* Coming Soon */}
                                                <motion.div
                                                    custom={2}
                                                    variants={sectionVariants}
                                                    initial="hidden"
                                                    animate="visible"
                                                    className="space-y-4"
                                                >
                                                    <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                                                        Coming Soon
                                                    </h3>
                                                    <div className="grid gap-4 sm:grid-cols-3">
                                                        {['Google', 'Apple', 'Outlook'].map((provider) => (
                                                            <Card key={provider} className="border-dashed border-2 opacity-60">
                                                                <CardContent className="pt-6 text-center">
                                                                    <p className="font-medium">{provider}</p>
                                                                    <p className="text-sm text-muted-foreground">Email & Calendar</p>
                                                                </CardContent>
                                                            </Card>
                                                        ))}
                                                    </div>
                                                </motion.div>

                                                <div className="flex justify-end gap-3 pt-4">
                                                    <Button
                                                        type="button"
                                                        variant="outline"
                                                        onClick={handleTestConnection}
                                                        disabled={isTesting}
                                                        className="gap-2"
                                                    >
                                                        {isTesting ? (
                                                            <Loader2 className="h-4 w-4 animate-spin" />
                                                        ) : (
                                                            <TestTube className="h-4 w-4" />
                                                        )}
                                                        {isTesting ? 'Testing...' : 'Test Connection'}
                                                    </Button>
                                                    <Button type="submit" disabled={isSaving} className="gap-2">
                                                        {isSaving && <Loader2 className="h-4 w-4 animate-spin" />}
                                                        <Save className="h-4 w-4" />
                                                        Save Configuration
                                                    </Button>
                                                </div>
                                            </form>
                                        </CardContent>
                                    </Card>
                                )}
                            </motion.div>
                        </TabsContent>
                    </AnimatePresence>
                </Tabs>
            </div>
        </div>
    );
}