import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Mail, Save, Loader2, Eye, EyeOff, TestTube, CheckCircle, XCircle } from 'lucide-react';
import { useBusiness, useBusinessEmailConfig } from '@/hooks/useBusiness';
import { supabase } from '@/integrations/supabase/client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { toast } from 'sonner';

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

export default function EmailConfigSettings() {
  const { business, isLoading: isLoadingBusiness } = useBusiness();
  const { emailConfig, isLoading: isLoadingConfig, saveEmailConfig, isSaving } = useBusinessEmailConfig(business?.id);
  
  const [showPassword, setShowPassword] = useState(false);
  const [formData, setFormData] = useState({
    smtp_host: '',
    smtp_port: 587,
    smtp_username: '',
    smtp_password: '',
    smtp_encryption: 'tls',
    from_email: '',
    from_name: '',
    reply_to_email: '',
    is_active: false,
  });

  useEffect(() => {
    if (emailConfig) {
      setFormData({
        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]);

  const handleSubmit = 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',
        ...formData,
      });
    } catch (error) {
      // Error handled in hook
    }
  };

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

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

    if (!formData.smtp_host || !formData.smtp_username || !formData.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-64">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!business) {
    return (
      <div className="p-6 max-w-3xl animate-fade-in">
        <Card className="border-dashed">
          <CardHeader className="text-center">
            <Mail className="h-12 w-12 mx-auto text-muted-foreground" />
            <CardTitle>No Business Configured</CardTitle>
            <CardDescription>
              Please create a business first before configuring email settings.
            </CardDescription>
          </CardHeader>
          <CardContent className="text-center">
            <Button asChild>
              <a href="/settings/business">Configure Business</a>
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-8 max-w-3xl animate-fade-in">
      <div>
        <h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
          <Mail className="h-6 w-6" />
          Email Configuration
        </h1>
        <p className="text-muted-foreground mt-1">
          Configure SMTP settings for sending emails from your business
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-8">
        {/* SMTP Server */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="space-y-4"
        >
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold">SMTP Server</h2>
            <div className="flex items-center gap-2">
              <Label htmlFor="is_active" className="text-sm text-muted-foreground">
                Enable email sending
              </Label>
              <Switch
                id="is_active"
                checked={formData.is_active}
                onCheckedChange={(checked) => setFormData(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={formData.smtp_host}
                onChange={(e) => setFormData(prev => ({ ...prev, smtp_host: e.target.value }))}
                placeholder="smtp.gmail.com"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="smtp_port">SMTP Port</Label>
              <Input
                id="smtp_port"
                type="number"
                value={formData.smtp_port}
                onChange={(e) => setFormData(prev => ({ ...prev, smtp_port: parseInt(e.target.value) || 587 }))}
                placeholder="587"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="smtp_username">Username</Label>
              <Input
                id="smtp_username"
                value={formData.smtp_username}
                onChange={(e) => setFormData(prev => ({ ...prev, smtp_username: e.target.value }))}
                placeholder="your-email@gmail.com"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="smtp_password">Password</Label>
              <div className="relative">
                <Input
                  id="smtp_password"
                  type={showPassword ? 'text' : 'password'}
                  value={formData.smtp_password}
                  onChange={(e) => setFormData(prev => ({ ...prev, smtp_password: e.target.value }))}
                  placeholder="App password"
                  className="pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {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={formData.smtp_encryption}
                onValueChange={(value) => setFormData(prev => ({ ...prev, smtp_encryption: value }))}
              >
                <SelectTrigger>
                  <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
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="space-y-4"
        >
          <h2 className="text-lg font-semibold">Sender Information</h2>
          <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={formData.from_name}
                onChange={(e) => setFormData(prev => ({ ...prev, from_name: e.target.value }))}
                placeholder="Your Business Name"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="from_email">From Email</Label>
              <Input
                id="from_email"
                type="email"
                value={formData.from_email}
                onChange={(e) => setFormData(prev => ({ ...prev, from_email: e.target.value }))}
                placeholder="noreply@yourdomain.com"
              />
            </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={formData.reply_to_email}
                onChange={(e) => setFormData(prev => ({ ...prev, reply_to_email: e.target.value }))}
                placeholder="support@yourdomain.com"
              />
            </div>
          </div>
        </motion.div>

        <Separator />

        {/* Future Integrations */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="space-y-4"
        >
          <h2 className="text-lg font-semibold">Coming Soon</h2>
          <div className="grid gap-4 sm:grid-cols-3">
            {['Google', 'Apple', 'Outlook'].map((provider) => (
              <Card key={provider} className="border-dashed 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-2 pt-4">
          <Button 
            type="button" 
            variant="outline" 
            onClick={handleTestConnection}
            disabled={isTesting}
          >
            {isTesting ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <TestTube className="mr-2 h-4 w-4" />
            )}
            {isTesting ? 'Testing...' : 'Test Connection'}
          </Button>
          <Button type="submit" disabled={isSaving}>
            {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            <Save className="mr-2 h-4 w-4" />
            Save Configuration
          </Button>
        </div>
      </form>
    </div>
  );
}
