import { useState } from 'react';
import { emailAPI } 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 { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { 
  Send, 
  Loader2,
  CheckCircle,
  ArrowLeft,
  Mail
} from 'lucide-react';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';

export default function SendEmail() {
  const [isSending, setIsSending] = useState(false);
  const [isHtml, setIsHtml] = useState(false);
  const [formData, setFormData] = useState({
    to_email: '',
    subject: '',
    body: '',
    from_name: '',
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.to_email || !formData.subject || !formData.body) {
      toast.error('Please fill in all required fields');
      return;
    }

    setIsSending(true);
    try {
      const response = await emailAPI.send({
        ...formData,
        is_html: isHtml,
      });

      if (response.success) {
        toast.success('Email sent successfully!');
        setFormData({
          to_email: '',
          subject: '',
          body: '',
          from_name: '',
        });
      } else {
        toast.error(response.message || 'Failed to send email');
      }
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Failed to send email');
    } finally {
      setIsSending(false);
    }
  };

  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">Send Email</h1>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Mail className="h-5 w-5" />
              Compose Email
            </CardTitle>
            <CardDescription>
              Send an email using your configured SMTP server
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="space-y-2">
                <Label htmlFor="to_email">To Email *</Label>
                <Input
                  id="to_email"
                  type="email"
                  placeholder="recipient@example.com"
                  value={formData.to_email}
                  onChange={(e) => setFormData({ ...formData, to_email: e.target.value })}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="from_name">From Name (Optional)</Label>
                <Input
                  id="from_name"
                  placeholder="Your Name or Company"
                  value={formData.from_name}
                  onChange={(e) => setFormData({ ...formData, from_name: e.target.value })}
                />
                <p className="text-xs text-gray-500">
                  This will be shown as the sender name
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="subject">Subject *</Label>
                <Input
                  id="subject"
                  placeholder="Email subject"
                  value={formData.subject}
                  onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                  required
                />
              </div>

              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <Label htmlFor="body">Message *</Label>
                  <div className="flex items-center space-x-2">
                    <Switch
                      id="is_html"
                      checked={isHtml}
                      onCheckedChange={setIsHtml}
                    />
                    <Label htmlFor="is_html" className="text-sm cursor-pointer">
                      HTML Content
                    </Label>
                  </div>
                </div>
                <Textarea
                  id="body"
                  placeholder={isHtml ? '<h1>Hello</h1><p>Your message here...</p>' : 'Your message here...'}
                  value={formData.body}
                  onChange={(e) => setFormData({ ...formData, body: e.target.value })}
                  rows={10}
                  required
                />
                <p className="text-xs text-gray-500">
                  {isHtml 
                    ? 'Enter valid HTML content. Make sure to include proper HTML tags.' 
                    : 'Plain text content will be sent as-is.'}
                </p>
              </div>

              <Button
                type="submit"
                className="w-full"
                disabled={isSending}
              >
                {isSending ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Sending...
                  </>
                ) : (
                  <>
                    <Send className="mr-2 h-4 w-4" />
                    Send Email
                  </>
                )}
              </Button>
            </form>
          </CardContent>
        </Card>

        {/* Tips Card */}
        <Card className="mt-6">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-green-600">
              <CheckCircle className="h-5 w-5" />
              Tips
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-sm text-gray-600">
            <p>• Make sure you have configured an SMTP server before sending emails</p>
            <p>• For HTML emails, use inline CSS for better compatibility</p>
            <p>• Test your emails with different email clients</p>
            <p>• Check your spam folder if emails are not received</p>
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
