"use client";

import {
  faBuilding,
  faCircleInfo,
  faCode,
  faSave,
  faServer,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useState } from "react";
import Toast from "@/components/ui/Toast";
import { useAdminToast } from "@/hooks/admin/useAdminToast";
import AdminPageHeader from "@/components/admin/AdminPageHeader";
import AdminCard from "@/components/admin/AdminCard";
import AdminForm from "@/components/admin/AdminForm";
import AdminSection from "@/components/admin/AdminSection";
import AdminInput from "@/components/admin/AdminInput";
import AdminTextarea from "@/components/admin/AdminTextarea";
import AdminButton from "@/components/admin/AdminButton";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import AdminTabNavigation from "@/components/admin/AdminTabNavigation";
import { adminFetch } from "@/lib/adminFetch";

interface EmailSettings {
  id: number;
  smtpHost: string;
  smtpPort: number;
  smtpUser: string;
  smtpPassword: string;
  companyEmail: string;
  companyName: string;
  confirmationTemplate: string;
  notificationTemplate: string;
}

type Tab = "company" | "smtp" | "templates";

const TABS = [
  { id: "company", label: "Company", icon: faBuilding },
  { id: "smtp", label: "SMTP", icon: faServer },
  { id: "templates", label: "Templates", icon: faCode },
] as const;

const DEFAULT_CONFIRMATION_TEMPLATE = `<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background-color: #B87333; color: white; padding: 20px; text-align: center; }
        .content { padding: 20px; background-color: #f9f9f9; }
        .footer { text-align: center; padding: 20px; font-size: 12px; color: #666; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Thank You for Contacting Us!</h1>
        </div>
        <div class="content">
            <p>Dear {name},</p>
            <p>Thank you for reaching out to Nitescape Lighting. We have received your message and will get back to you as soon as possible.</p>
            <p>Here's a summary of your message:</p>
            <ul>
                <li><strong>Subject:</strong> {subject}</li>
                <li><strong>Message:</strong> {message}</li>
            </ul>
            <p>If you have any additional information to share, please don't hesitate to reply to this email.</p>
            <p>Best regards,<br>The Nitescape Lighting Team</p>
        </div>
        <div class="footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>© 2024 Nitescape Lighting. All rights reserved.</p>
        </div>
    </div>
</body>
</html>`;

const DEFAULT_NOTIFICATION_TEMPLATE = `<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background-color: #B87333; color: white; padding: 20px; text-align: center; }
        .content { padding: 20px; background-color: #f9f9f9; }
        .contact-info { background-color: #f0f0f0; padding: 15px; margin: 15px 0; border-radius: 5px; }
        .footer { text-align: center; padding: 20px; font-size: 12px; color: #666; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>New Contact Form Submission</h1>
        </div>
        <div class="content">
            <p>A new message has been received through the contact form:</p>

            <div class="contact-info">
                <h3>Contact Information:</h3>
                <p><strong>Name:</strong> {name}</p>
                <p><strong>Email:</strong> {email}</p>
                <p><strong>Subject:</strong> {subject}</p>
            </div>

            <h3>Message:</h3>
            <p>{message}</p>

            <p>Please respond to this inquiry at your earliest convenience.</p>
        </div>
        <div class="footer">
            <p>This is an automated notification from your website's contact form.</p>
            <p>© 2024 Nitescape Lighting. All rights reserved.</p>
        </div>
    </div>
</body>
</html>`;

export default function AdminEmail() {
  const [settings, setSettings] = useState<EmailSettings>({
    id: 0,
    smtpHost: "",
    smtpPort: 587,
    smtpUser: "",
    smtpPassword: "",
    companyEmail: "",
    companyName: "",
    confirmationTemplate: DEFAULT_CONFIRMATION_TEMPLATE,
    notificationTemplate: DEFAULT_NOTIFICATION_TEMPLATE,
  });
  const [activeTab, setActiveTab] = useState<Tab>("company");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { toast, showSuccess, showError, hideToast } = useAdminToast();

  useEffect(() => {
    fetchSettings();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchSettings = async () => {
    try {
      const response = await fetch("/api/email/settings");
      const data = await response.json();
      if (data) {
        setSettings(data);
      }
    } catch {
      showError("Failed to load email settings");
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const response = await adminFetch("/api/email/settings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(settings),
      });

      if (!response.ok) throw new Error("Failed to save settings");

      showSuccess("Email settings saved successfully!");
    } catch {
      showError("Failed to save email settings");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <>
        <AdminPageHeader title="Email" description="Configure email settings" />
        <AdminLoadingState message="Loading email settings..." />
      </>
    );
  }

  return (
    <>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
      <AdminPageHeader
        title="Email"
        description="SMTP credentials, transactional email templates, and sender info"
      />

      <AdminTabNavigation
        tabs={TABS as unknown as { id: string; label: string; icon: any }[]}
        activeTab={activeTab}
        onTabChange={(id) => setActiveTab(id as Tab)}
        className="mb-6"
      />

      <AdminCard>
        <AdminForm onSubmit={handleSubmit}>
          {activeTab === "company" && (
            <AdminSection
              title="Company information"
              description="The sender identity used in outgoing emails"
            >
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <AdminInput
                  label="Company name"
                  name="companyName"
                  value={settings.companyName}
                  onChange={(e) =>
                    setSettings({ ...settings, companyName: e.target.value })
                  }
                  required
                />
                <AdminInput
                  label="Company email"
                  type="email"
                  name="companyEmail"
                  value={settings.companyEmail}
                  onChange={(e) =>
                    setSettings({ ...settings, companyEmail: e.target.value })
                  }
                  required
                />
              </div>
            </AdminSection>
          )}

          {activeTab === "smtp" && (
            <AdminSection
              title="SMTP settings"
              description="Outgoing mail server configuration"
            >
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <AdminInput
                  label="SMTP host"
                  name="smtpHost"
                  value={settings.smtpHost}
                  onChange={(e) =>
                    setSettings({ ...settings, smtpHost: e.target.value })
                  }
                  placeholder="smtp.example.com"
                  required
                />
                <AdminInput
                  label="SMTP port"
                  type="number"
                  name="smtpPort"
                  value={settings.smtpPort}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      smtpPort: parseInt(e.target.value) || 587,
                    })
                  }
                  required
                />
              </div>
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <AdminInput
                  label="SMTP username"
                  name="smtpUser"
                  value={settings.smtpUser}
                  onChange={(e) =>
                    setSettings({ ...settings, smtpUser: e.target.value })
                  }
                  required
                />
                <AdminInput
                  label="SMTP password"
                  type="password"
                  name="smtpPassword"
                  value={settings.smtpPassword}
                  onChange={(e) =>
                    setSettings({ ...settings, smtpPassword: e.target.value })
                  }
                  required
                />
              </div>
            </AdminSection>
          )}

          {activeTab === "templates" && (
            <AdminSection
              title="Email templates"
              description="Customize transactional email HTML. Use {name}, {email}, {subject}, {message} as placeholders."
            >
              <AdminTextarea
                label="Confirmation template"
                name="confirmationTemplate"
                value={settings.confirmationTemplate}
                onChange={(e) =>
                  setSettings({ ...settings, confirmationTemplate: e.target.value })
                }
                rows={14}
                className="font-mono text-xs"
              />
              <AdminTextarea
                label="Notification template"
                name="notificationTemplate"
                value={settings.notificationTemplate}
                onChange={(e) =>
                  setSettings({ ...settings, notificationTemplate: e.target.value })
                }
                rows={14}
                className="font-mono text-xs"
              />
            </AdminSection>
          )}

          <div className="-mx-6 -mb-6 mt-8 flex justify-end border-t border-slate-800 bg-slate-900/50 px-6 py-4">
            <AdminButton
              type="submit"
              variant="primary"
              isLoading={saving}
              icon={faSave}
            >
              Save changes
            </AdminButton>
          </div>
        </AdminForm>
      </AdminCard>

      <div className="mt-6 flex items-start gap-3 rounded-lg border border-slate-800 bg-slate-900/50 p-4 text-sm text-slate-400">
        <FontAwesomeIcon
          icon={faCircleInfo}
          className="mt-0.5 h-4 w-4 shrink-0 text-indigo-300"
        />
        <div>
          <strong className="font-medium text-slate-200">Tip:</strong> Send a test
          submission through the public contact form to verify SMTP is working after any
          changes.
        </div>
      </div>
    </>
  );
}
