// components/CreateEmailModal.tsx
"use client";

import { useEffect, useState, FormEvent } from "react";
import { X, Loader2, AlertCircle, Shuffle } from "lucide-react";

interface DomainOption {
  id: string;
  name: string;
  status: "PENDING" | "ACTIVE";
}

interface CreateEmailModalProps {
  onClose: () => void;
  onCreated: () => void;
}

const ADJECTIVES = ["swift", "quiet", "bold", "amber", "lucky", "clever", "brave", "calm"];
const NOUNS = ["otter", "falcon", "tiger", "maple", "harbor", "comet", "willow", "canyon"];

function clientSideRandomPrefix(): string {
  const adjective = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)];
  const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)];
  const suffix = Math.floor(1000 + Math.random() * 9000);
  return `${adjective}-${noun}-${suffix}`;
}

export default function CreateEmailModal({ onClose, onCreated }: CreateEmailModalProps) {
  const [domains, setDomains] = useState<DomainOption[]>([]);
  const [domainId, setDomainId] = useState("");
  const [prefix, setPrefix] = useState("");
  const [isLoadingDomains, setIsLoadingDomains] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function loadDomains() {
      try {
        const res = await fetch("/api/domains");
        const data = await res.json();
        if (res.ok) {
          const active = (data.domains as DomainOption[]).filter((d) => d.status === "ACTIVE");
          setDomains(active);
          if (active.length > 0) setDomainId(active[0].id);
        }
      } finally {
        setIsLoadingDomains(false);
      }
    }
    loadDomains();
  }, []);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);

    if (!domainId) {
      setError("Please select a verified domain");
      return;
    }

    setIsSubmitting(true);
    try {
      const res = await fetch("/api/emails", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ domainId, prefix: prefix.trim() || undefined }),
      });

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Failed to create email");
        setIsSubmitting(false);
        return;
      }

      onCreated();
      onClose();
    } catch {
      setError("Something went wrong. Please try again.");
      setIsSubmitting(false);
    }
  }

  const selectedDomain = domains.find((d) => d.id === domainId);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4">
      <div className="w-full max-w-md bg-slate-900 border border-slate-800 rounded-2xl shadow-xl">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-800">
          <h2 className="text-sm font-semibold text-white">Create Temp Email</h2>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-5 space-y-4">
          {error && (
            <div className="flex items-center gap-2 text-sm text-red-400 bg-red-950/40 border border-red-900 rounded-lg px-3 py-2">
              <AlertCircle className="w-4 h-4 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          <div className="space-y-1.5">
            <label htmlFor="domain-select" className="text-xs font-medium text-slate-400">
              Domain
            </label>
            {isLoadingDomains ? (
              <div className="text-sm text-slate-500 py-2">Loading domains...</div>
            ) : domains.length === 0 ? (
              <div className="text-sm text-amber-400 bg-amber-950/40 border border-amber-900 rounded-lg px-3 py-2">
                No verified domains available. Add and verify a domain first.
              </div>
            ) : (
              <select
                id="domain-select"
                value={domainId}
                onChange={(e) => setDomainId(e.target.value)}
                className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2.5 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                disabled={isSubmitting}
              >
                {domains.map((d) => (
                  <option key={d.id} value={d.id}>
                    {d.name}
                  </option>
                ))}
              </select>
            )}
          </div>

          <div className="space-y-1.5">
            <label htmlFor="prefix" className="text-xs font-medium text-slate-400">
              Prefix (optional)
            </label>
            <div className="flex gap-2">
              <input
                id="prefix"
                type="text"
                value={prefix}
                onChange={(e) => setPrefix(e.target.value)}
                placeholder="leave blank to auto-generate"
                className="flex-1 min-w-0 bg-slate-800 border border-slate-700 rounded-lg px-3 py-2.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                disabled={isSubmitting}
              />
              <button
                type="button"
                onClick={() => setPrefix(clientSideRandomPrefix())}
                disabled={isSubmitting}
                className="shrink-0 flex items-center gap-1.5 px-3 py-2.5 text-xs font-medium bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-colors"
                title="Auto-generate random name"
              >
                <Shuffle className="w-3.5 h-3.5" />
                Random
              </button>
            </div>
            {selectedDomain && (
              <p className="text-xs text-slate-500 font-mono truncate">
                {prefix.trim() || "<auto-generated>"}@{selectedDomain.name}
              </p>
            )}
          </div>

          <div className="flex justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={onClose}
              disabled={isSubmitting}
              className="px-4 py-2 text-sm font-medium text-slate-300 hover:text-white transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting || domains.length === 0}
              className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-indigo-600 hover:bg-indigo-500 disabled:bg-indigo-900 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
            >
              {isSubmitting && <Loader2 className="w-4 h-4 animate-spin" />}
              Create Email
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
