"use client";

import { useCallback, useEffect, useState } from "react";
import {
  fetchEmailRequests,
  createEmailRequest,
  updateEmailRequest,
  deleteEmailRequest,
  type EmailRequest,
  type CreateEmailRequestDto,
  type UpdateEmailRequestDto,
} from "@/lib/api/emailRequests";
import { Pencil, Trash2, Plus, X } from "lucide-react";
import { formatDate } from "@/lib/dateFormattingUtility";
export default function AdminEmailPage() {
  const [emails, setEmails] = useState<EmailRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [modalMode, setModalMode] = useState<"create" | "edit">("create");
  const [selectedEmail, setSelectedEmail] = useState<EmailRequest | null>(null);
  const [formData, setFormData] = useState<CreateEmailRequestDto>({
    email: "",
    status: "",
  });
  const [submitting, setSubmitting] = useState(false);

  const loadEmails = useCallback(async () => {
    try {
      setLoading(true);
      const data = await fetchEmailRequests();
      setEmails(data);
      setError(null);
    } catch (e: any) {
      console.error(e);
      setError(e?.message ?? "Failed to load email requests");
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleCreate = () => {
    setModalMode("create");
    setFormData({ email: "", status: "" });
    setSelectedEmail(null);
    setShowModal(true);
  };

  const handleEdit = (email: EmailRequest) => {
    setModalMode("edit");
    setFormData({ email: email.email, status: email.status });
    setSelectedEmail(email);
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Are you sure you want to delete this email request?")) return;

    try {
      await deleteEmailRequest(id);
      await loadEmails();
    } catch (e: any) {
      alert(e?.message ?? "Failed to delete email request");
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setSubmitting(true);
      if (modalMode === "create") {
        await createEmailRequest(formData);
      } else if (selectedEmail) {
        const updateData: UpdateEmailRequestDto = {};
        if (formData.email !== selectedEmail.email) updateData.email = formData.email;
        if (formData.status !== selectedEmail.status) updateData.status = formData.status;
        await updateEmailRequest(selectedEmail.id, updateData);
      }
      setShowModal(false);
      await loadEmails();
    } catch (e: any) {
      alert(e?.message ?? "Failed to save email request");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="p-6 space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-lg font-semibold tracking-tight">
            Processed E-mail
          </h1>
          <p className="mt-1 text-xs text-zinc-400">
            Manage email requests and their statuses.
          </p>
        </div>
        <button
          onClick={handleCreate}
          className="flex items-center gap-2 rounded-md bg-emerald-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-emerald-500"
        >
          <Plus size={14} />
          Add Email Request
        </button>
      </div>

      {/* Error */}
      {error && (
        <div className="rounded border border-red-500/60 bg-red-950/30 px-3 py-2 text-xs text-red-200">
          {error}
        </div>
      )}

      {/* Table */}
      {loading ? (
        <div className="text-sm text-zinc-400">Loading…</div>
      ) : (
        <div className="overflow-x-auto rounded-lg border border-zinc-800 bg-zinc-950/60">
          <table className="min-w-full text-left text-xs">
            <thead className="bg-zinc-900/80 text-zinc-400">
              <tr>
                <th className="px-3 py-2 font-medium">ID</th>
                <th className="px-3 py-2 font-medium">Email</th>
                <th className="px-3 py-2 font-medium">Status</th>
                <th className="px-3 py-2 font-medium">Created At</th>
                <th className="px-3 py-2 font-medium">Updated At</th>
                <th className="px-3 py-2 font-medium text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {emails.map((email) => (
                <tr
                  key={email.id}
                  className="border-t border-zinc-800/70 hover:bg-zinc-900/60"
                >
                  <td className="px-3 py-2 text-zinc-400">{email.id}</td>
                  <td className="px-3 py-2 text-zinc-100">{email.recipient}</td>
                  <td className="px-3 py-2">
                    <span className="inline-flex items-center rounded-full bg-zinc-800 px-2 py-0.5 text-[11px] text-zinc-300">
                      {email.status}
                    </span>
                  </td>
                  <td className="px-3 py-2 text-[11px] text-zinc-400">
                    {new Date(email.createdAt).toLocaleString()}
                  </td>
                  <td className="px-3 py-2 text-[11px] text-zinc-400">
                    {formatDate(email.updatedAt)}
                  </td>
                  <td className="px-3 py-2 text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleEdit(email)}
                        className="rounded p-1 text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100"
                        title="Edit"
                      >
                        <Pencil size={14} />
                      </button>
                      <button
                        onClick={() => handleDelete(email.id)}
                        className="rounded p-1 text-zinc-400 hover:bg-red-900/50 hover:text-red-400"
                        title="Delete"
                      >
                        <Trash2 size={14} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}

              {emails.length === 0 && (
                <tr>
                  <td
                    colSpan={6}
                    className="px-3 py-4 text-center text-xs text-zinc-500"
                  >
                    No email requests found.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
          <div className="w-full max-w-md rounded-lg border border-zinc-800 bg-zinc-950 p-6 shadow-xl">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-base font-semibold">
                {modalMode === "create" ? "Create Email Request" : "Edit Email Request"}
              </h2>
              <button
                onClick={() => setShowModal(false)}
                className="rounded p-1 text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100"
              >
                <X size={16} />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="mb-1 block text-xs font-medium text-zinc-300">
                  Email
                </label>
                <input
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  className="w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-500 focus:border-emerald-500 focus:outline-none focus:ring-1 focus:ring-emerald-500"
                  placeholder="user@example.com"
                  required
                />
              </div>

              <div>
                <label className="mb-1 block text-xs font-medium text-zinc-300">
                  Status
                </label>
                <input
                  type="text"
                  value={formData.status}
                  onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                  className="w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-500 focus:border-emerald-500 focus:outline-none focus:ring-1 focus:ring-emerald-500"
                  placeholder="pending"
                />
              </div>

              <div className="flex gap-2 pt-2">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="flex-1 rounded-md border border-zinc-700 px-4 py-2 text-xs font-medium text-zinc-300 hover:bg-zinc-800"
                  disabled={submitting}
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 rounded-md bg-emerald-600 px-4 py-2 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50"
                  disabled={submitting}
                >
                  {submitting ? "Saving..." : modalMode === "create" ? "Create" : "Update"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
