import { useEffect, useState } from 'react';
import { smtpAPI } from '@/services/api';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { 
  Settings, 
  Plus, 
  Edit2, 
  Trash2, 
  CheckCircle,
  Loader2,
  Server,
  ArrowLeft,
  Star
} from 'lucide-react';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';

interface SmtpConfig {
  id: number;
  name: string;
  host: string;
  port: number;
  username: string;
  use_tls: boolean;
  is_default: boolean;
  is_active: boolean;
  created_at: string;
}

export default function SmtpConfigs() {
  const [configs, setConfigs] = useState<SmtpConfig[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isCreating, setIsCreating] = useState(false);
  const [editingConfig, setEditingConfig] = useState<SmtpConfig | null>(null);
  const [configToDelete, setConfigToDelete] = useState<SmtpConfig | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    host: '',
    port: 587,
    username: '',
    password: '',
    use_tls: true,
    is_default: false,
  });

  useEffect(() => {
    loadConfigs();
  }, []);

  const loadConfigs = async () => {
    try {
      const data = await smtpAPI.getAll();
      setConfigs(data);
    } catch (error) {
      toast.error('Failed to load SMTP configurations');
    } finally {
      setIsLoading(false);
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      host: '',
      port: 587,
      username: '',
      password: '',
      use_tls: true,
      is_default: false,
    });
  };

  const handleCreate = async () => {
    if (!formData.name || !formData.host || !formData.username || !formData.password) {
      toast.error('Please fill in all required fields');
      return;
    }

    setIsCreating(true);
    try {
      await smtpAPI.create(formData);
      toast.success('SMTP configuration created');
      resetForm();
      await loadConfigs();
    } catch (error) {
      toast.error('Failed to create SMTP configuration');
    } finally {
      setIsCreating(false);
    }
  };

  const handleUpdate = async () => {
    if (!editingConfig) return;

    try {
      await smtpAPI.update(editingConfig.id, {
        name: formData.name,
        host: formData.host,
        port: formData.port,
        username: formData.username,
        password: formData.password || undefined,
        use_tls: formData.use_tls,
        is_default: formData.is_default,
      });
      toast.success('SMTP configuration updated');
      setEditingConfig(null);
      resetForm();
      await loadConfigs();
    } catch (error) {
      toast.error('Failed to update SMTP configuration');
    }
  };

  const handleDelete = async () => {
    if (!configToDelete) return;

    try {
      await smtpAPI.delete(configToDelete.id);
      toast.success('SMTP configuration deleted');
      setConfigToDelete(null);
      await loadConfigs();
    } catch (error) {
      toast.error('Failed to delete SMTP configuration');
    }
  };

  const startEdit = (config: SmtpConfig) => {
    setEditingConfig(config);
    setFormData({
      name: config.name,
      host: config.host,
      port: config.port,
      username: config.username,
      password: '',
      use_tls: config.use_tls,
      is_default: config.is_default,
    });
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center gap-4">
              <Link to="/dashboard">
                <Button variant="ghost" size="sm">
                  <ArrowLeft className="h-4 w-4 mr-2" />
                  Back
                </Button>
              </Link>
              <h1 className="text-xl font-bold text-gray-900">SMTP Configurations</h1>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Card>
          <CardHeader>
            <div className="flex justify-between items-start">
              <div>
                <CardTitle className="flex items-center gap-2">
                  <Server className="h-5 w-5" />
                  Your SMTP Servers
                </CardTitle>
                <CardDescription>
                  Configure SMTP servers to send emails from your applications
                </CardDescription>
              </div>
              <Dialog>
                <DialogTrigger asChild>
                  <Button onClick={resetForm}>
                    <Plus className="h-4 w-4 mr-2" />
                    Add SMTP Config
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-lg">
                  <DialogHeader>
                    <DialogTitle>Add SMTP Configuration</DialogTitle>
                    <DialogDescription>
                      Enter your SMTP server details
                    </DialogDescription>
                  </DialogHeader>
                  <div className="space-y-4 py-4">
                    <div className="space-y-2">
                      <Label htmlFor="name">Configuration Name *</Label>
                      <Input
                        id="name"
                        placeholder="e.g., Gmail SMTP, SendGrid"
                        value={formData.name}
                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="host">SMTP Host *</Label>
                        <Input
                          id="host"
                          placeholder="smtp.gmail.com"
                          value={formData.host}
                          onChange={(e) => setFormData({ ...formData, host: e.target.value })}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="port">Port *</Label>
                        <Input
                          id="port"
                          type="number"
                          value={formData.port}
                          onChange={(e) => setFormData({ ...formData, port: parseInt(e.target.value) })}
                        />
                      </div>
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="username">Username/Email *</Label>
                      <Input
                        id="username"
                        placeholder="your@email.com"
                        value={formData.username}
                        onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="password">Password/App Password *</Label>
                      <Input
                        id="password"
                        type="password"
                        placeholder="Your SMTP password"
                        value={formData.password}
                        onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                      />
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-2">
                        <Switch
                          id="use_tls"
                          checked={formData.use_tls}
                          onCheckedChange={(checked) => setFormData({ ...formData, use_tls: checked })}
                        />
                        <Label htmlFor="use_tls">Use TLS/SSL</Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Switch
                          id="is_default"
                          checked={formData.is_default}
                          onCheckedChange={(checked) => setFormData({ ...formData, is_default: checked })}
                        />
                        <Label htmlFor="is_default">Set as Default</Label>
                      </div>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button onClick={handleCreate} disabled={isCreating}>
                      {isCreating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                      Add Configuration
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>
          </CardHeader>
          <CardContent>
            {configs.length === 0 ? (
              <div className="text-center py-12">
                <Server className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">No SMTP configurations</h3>
                <p className="text-gray-500 mb-4">Add your first SMTP server to start sending emails</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {configs.map((config) => (
                  <Card key={config.id} className={config.is_default ? 'border-blue-500 border-2' : ''}>
                    <CardHeader className="pb-3">
                      <div className="flex justify-between items-start">
                        <div className="flex items-center gap-2">
                          <CardTitle className="text-lg">{config.name}</CardTitle>
                          {config.is_default && (
                            <Badge className="bg-blue-100 text-blue-800">
                              <Star className="h-3 w-3 mr-1" />
                              Default
                            </Badge>
                          )}
                        </div>
                        <div className="flex gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => startEdit(config)}
                          >
                            <Edit2 className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setConfigToDelete(config)}
                          >
                            <Trash2 className="h-4 w-4 text-red-500" />
                          </Button>
                        </div>
                      </div>
                      <CardDescription>
                        {config.host}:{config.port}
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-2">
                      <div className="flex items-center gap-2 text-sm">
                        <Settings className="h-4 w-4 text-gray-400" />
                        <span className="text-gray-600">{config.username}</span>
                      </div>
                      <div className="flex items-center gap-2 text-sm">
                        {config.use_tls ? (
                          <CheckCircle className="h-4 w-4 text-green-500" />
                        ) : (
                          <Settings className="h-4 w-4 text-gray-400" />
                        )}
                        <span className="text-gray-600">
                          {config.use_tls ? 'TLS Enabled' : 'TLS Disabled'}
                        </span>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Common SMTP Settings */}
        <Card className="mt-6">
          <CardHeader>
            <CardTitle>Common SMTP Settings</CardTitle>
            <CardDescription>Reference for popular email providers</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-gray-50 p-4 rounded-lg">
                <h4 className="font-medium mb-2">Gmail</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>Host: smtp.gmail.com</li>
                  <li>Port: 587</li>
                  <li>TLS: Yes</li>
                  <li>Password: App Password required</li>
                </ul>
              </div>
              <div className="bg-gray-50 p-4 rounded-lg">
                <h4 className="font-medium mb-2">Outlook/Hotmail</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>Host: smtp.office365.com</li>
                  <li>Port: 587</li>
                  <li>TLS: Yes</li>
                  <li>Password: Your password</li>
                </ul>
              </div>
              <div className="bg-gray-50 p-4 rounded-lg">
                <h4 className="font-medium mb-2">Yahoo Mail</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>Host: smtp.mail.yahoo.com</li>
                  <li>Port: 587</li>
                  <li>TLS: Yes</li>
                  <li>Password: App Password required</li>
                </ul>
              </div>
            </div>
          </CardContent>
        </Card>
      </main>

      {/* Edit Dialog */}
      <Dialog open={!!editingConfig} onOpenChange={() => setEditingConfig(null)}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Edit SMTP Configuration</DialogTitle>
            <DialogDescription>
              Update your SMTP server details
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="edit_name">Configuration Name *</Label>
              <Input
                id="edit_name"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="edit_host">SMTP Host *</Label>
                <Input
                  id="edit_host"
                  value={formData.host}
                  onChange={(e) => setFormData({ ...formData, host: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit_port">Port *</Label>
                <Input
                  id="edit_port"
                  type="number"
                  value={formData.port}
                  onChange={(e) => setFormData({ ...formData, port: parseInt(e.target.value) })}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit_username">Username/Email *</Label>
              <Input
                id="edit_username"
                value={formData.username}
                onChange={(e) => setFormData({ ...formData, username: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit_password">Password (leave blank to keep current)</Label>
              <Input
                id="edit_password"
                type="password"
                placeholder="Enter new password to change"
                value={formData.password}
                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
              />
            </div>
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Switch
                  id="edit_use_tls"
                  checked={formData.use_tls}
                  onCheckedChange={(checked) => setFormData({ ...formData, use_tls: checked })}
                />
                <Label htmlFor="edit_use_tls">Use TLS/SSL</Label>
              </div>
              <div className="flex items-center space-x-2">
                <Switch
                  id="edit_is_default"
                  checked={formData.is_default}
                  onCheckedChange={(checked) => setFormData({ ...formData, is_default: checked })}
                />
                <Label htmlFor="edit_is_default">Set as Default</Label>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditingConfig(null)}>
              Cancel
            </Button>
            <Button onClick={handleUpdate}>
              Save Changes
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <Dialog open={!!configToDelete} onOpenChange={() => setConfigToDelete(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="text-red-600">Delete SMTP Configuration</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete "{configToDelete?.name}"? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfigToDelete(null)}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleDelete}>
              <Trash2 className="h-4 w-4 mr-2" />
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
