"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Plus,
  Globe,
  Shield,
  Key,
  Eye,
  EyeOff,
  Loader,
  Trash2,
  ExternalLink,
  Sparkles,
  CheckCircle2,
  Copy,
  Download,
  Zap,
  Eye as ViewIcon,
  ChevronLeft,
  ChevronRight,
  ArrowRight,
} from "lucide-react";

interface Website {
  id: number;
  siteUrl: string;
  siteName: string;
  authMethod: string;
  createdAt: string;
  metadata: {
    wp_username?: string;
    api_key?: string;
    connection_status?: string;
  };
}

export default function WebsitesPage() {
  const [websites, setWebsites] = useState<Website[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalStep, setModalStep] = useState(1);
  const [loginLoading, setLoginLoading] = useState<number | null>(null);

  // Pagination states
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 5;

  // Form states
  const [siteUrl, setSiteUrl] = useState("");
  const [siteName, setSiteName] = useState("");
  const [authMethod, setAuthMethod] = useState<
    "credentials" | "application_password" | "plugin_api_key"
  >("plugin_api_key");
  const [wpUsername, setWpUsername] = useState("admin");
  const [wpPassword, setWpPassword] = useState("");
  const [wpAppPassword, setWpAppPassword] = useState("");

  // States for response after adding site
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [newlyAddedSite, setNewlyAddedSite] = useState<any | null>(null);
  const [showPassword, setShowPassword] = useState(false);
  const [copiedKey, setCopiedKey] = useState(false);

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

  const fetchWebsites = async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/websites");
      const data = await res.json();
      if (res.ok) {
        setWebsites(data.websites);
        setCurrentPage(1); // reset to first page on load
      }
    } catch (err) {
      console.error("Error fetching websites:", err);
    } finally {
      setLoading(false);
    }
  };

  const handleAddWebsite = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);

    try {
      let formattedUrl = siteUrl.trim();
      if (!formattedUrl) {
        throw new Error("WordPress URL is required.");
      }

      if (!/^https?:\/\//i.test(formattedUrl)) {
        formattedUrl = "http://" + formattedUrl;
      }
      formattedUrl = formattedUrl.replace(/\/$/, "");

      // Store siteName label temporarily to retrieve it on redirect callback
      if (siteName.trim()) {
        sessionStorage.setItem("rp_pending_site_name", siteName.trim());
      } else {
        sessionStorage.removeItem("rp_pending_site_name");
      }

      const successUrl = encodeURIComponent(
        "http://localhost:3000/websites/auth-callback",
      );
      const rejectUrl = encodeURIComponent("http://localhost:3000/websites");

      const uniqueId = Math.floor(1000 + Math.random() * 9000); // 4-digit random number to prevent WP name collisions
      const appName = encodeURIComponent(`RemotePress-${uniqueId}`);

      // Redirect directly to the WordPress Application Authorization panel
      window.location.href = `${formattedUrl}/wp-admin/authorize-application.php?app_name=${appName}&success_url=${successUrl}&reject_url=${rejectUrl}`;
    } catch (err: any) {
      setError(err.message || "Invalid WordPress URL configuration.");
      setSubmitting(false);
    }
  };

  const handleDeleteWebsite = async (id: number) => {
    if (
      !confirm(
        "Are you sure you want to delete this website? This action cannot be undone.",
      )
    ) {
      return;
    }

    try {
      const res = await fetch(`/api/websites/${id}`, {
        method: "DELETE",
      });

      if (res.ok) {
        setWebsites(websites.filter((site) => site.id !== id));
        // Reset pagination index if empty page
        const newTotalItems = websites.length - 1;
        const maxPage = Math.ceil(newTotalItems / itemsPerPage) || 1;
        if (currentPage > maxPage) {
          setCurrentPage(maxPage);
        }
      } else {
        const data = await res.json();
        alert(data.error || "Failed to delete site.");
      }
    } catch (err) {
      console.error("Error deleting site:", err);
    }
  };

  const handleAutoLogin = async (siteId: number) => {
    try {
      setLoginLoading(siteId);
      const res = await fetch(`/api/websites/${siteId}/login-token`, {
        method: "POST",
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Failed to generate secure login token.");
      }

      // Launch secure redirect in a new tab!
      window.open(data.redirectUrl, "_blank");
    } catch (err: any) {
      alert(err.message || "Auto Login failed.");
    } finally {
      setLoginLoading(null);
    }
  };

  const resetForm = () => {
    setSiteUrl("");
    setSiteName("");
    setAuthMethod("plugin_api_key");
    setWpUsername("admin");
    setWpPassword("");
    setWpAppPassword("");
    setModalStep(1);
    setNewlyAddedSite(null);
    setError(null);
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    setCopiedKey(true);
    setTimeout(() => setCopiedKey(false), 2000);
  };

  const formatDate = (dateString: string) => {
    const d = new Date(dateString);
    return d.toLocaleDateString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  // Pagination calculations
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentWebsites = websites.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(websites.length / itemsPerPage) || 1;

  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const handleNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
    }
  };

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-slate-900 tracking-tight">
            Connected Websites
          </h1>
          <p className="text-slate-500 text-sm mt-1">
            Connect, monitor, and instantly access your WordPress dashboards
          </p>
        </div>

        <button
          onClick={() => {
            resetForm();
            setModalOpen(true);
          }}
          className="px-4 py-2.5 rounded-xl bg-slate-900 hover:bg-slate-800 font-bold text-sm text-white transition-colors flex items-center gap-2 cursor-pointer shadow-sm"
        >
          <Plus className="h-5 w-5" /> Add Website
        </button>
      </div>

      {/* Websites Table List */}
      {loading ? (
        <div className="w-full bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-4">
          <div className="h-8 bg-slate-100 rounded animate-pulse w-full" />
          <div className="h-12 bg-slate-50 rounded animate-pulse w-full" />
          <div className="h-12 bg-slate-50 rounded animate-pulse w-full" />
          <div className="h-12 bg-slate-50 rounded animate-pulse w-full" />
        </div>
      ) : websites.length === 0 ? (
        <div className="glass-panel p-16 rounded-2xl text-center max-w-xl mx-auto border border-slate-200 bg-white">
          <div className="w-12 h-12 rounded-2xl bg-slate-50 flex items-center justify-center mx-auto mb-4 border border-slate-200">
            <Globe className="h-6 w-6 text-slate-600" />
          </div>
          <h3 className="text-lg font-bold text-slate-800 mb-2">
            No Websites Added Yet
          </h3>
          <p className="text-sm text-slate-500 mb-6 leading-relaxed">
            Get started by adding your first WordPress website. Connect using
            credentials, application passwords, or our lightweight API plugin.
          </p>
          <button
            onClick={() => {
              resetForm();
              setModalOpen(true);
            }}
            className="px-5 py-2.5 rounded-xl bg-slate-900 hover:bg-slate-800 font-bold text-sm text-white transition-colors cursor-pointer"
          >
            Connect First Website
          </button>
        </div>
      ) : (
        <div className="glass-panel rounded-2xl border border-slate-200 bg-white shadow-sm flex flex-col justify-between overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-slate-200 bg-slate-50 text-slate-500 font-bold text-[10.5px] uppercase tracking-wider">
                  <th className="px-6 py-4 font-bold">Site Name / URL</th>
                  <th className="px-6 py-4 font-bold">Connection Status</th>
                  <th className="px-6 py-4 font-bold">Date Added</th>
                  <th className="px-6 py-4 text-right font-bold">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 text-sm text-slate-700 bg-white">
                {currentWebsites.map((site) => {
                  // Determine Connection status badge mapped strictly to Connected / Disconnected / Disabled
                  let statusBadge = (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10.5px] font-bold bg-slate-100 text-slate-600 border border-slate-200">
                      <span className="w-1.5 h-1.5 rounded-full bg-slate-400" />{" "}
                      Disabled
                    </span>
                  );

                  if (site.metadata.connection_status === "disabled") {
                    statusBadge = (
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10.5px] font-bold bg-slate-100 text-slate-600 border border-slate-200">
                        <span className="w-1.5 h-1.5 rounded-full bg-slate-400" />{" "}
                        Disabled
                      </span>
                    );
                  } else if (site.authMethod === "plugin_api_key") {
                    const connected =
                      site.metadata.connection_status === "connected";
                    statusBadge = connected ? (
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10.5px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
                        <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />{" "}
                        Connected
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10.5px] font-bold bg-red-50 text-red-750 border border-red-200">
                        <span className="w-1.5 h-1.5 rounded-full bg-red-500" />{" "}
                        Disconnected
                      </span>
                    );
                  } else {
                    // Default to Connected for credentials method unless specified
                    statusBadge = (
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10.5px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
                        <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />{" "}
                        Connected
                      </span>
                    );
                  }

                  return (
                    <tr
                      key={site.id}
                      className="hover:bg-slate-50 transition-colors group"
                    >
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded bg-slate-100 border border-slate-200 flex items-center justify-center shrink-0">
                            <span className="text-slate-600 font-extrabold text-xs">
                              WP
                            </span>
                          </div>
                          <div className="overflow-hidden max-w-[250px] sm:max-w-[400px]">
                            <p
                              className="font-semibold text-slate-800 truncate"
                              title={site.siteName}
                            >
                              <a href={`/websites/${site.id}`}>
                                {site.siteName}
                              </a>
                            </p>
                            <a
                              href={`/websites/${site.id}`}
                              className="text-xs text-slate-400 hover:text-blue-600 inline-flex items-center gap-0.5 truncate font-medium"
                            >
                              {site.siteUrl.replace(/^https?:\/\/(www\.)?/, "")}
                            </a>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">{statusBadge}</td>
                      <td className="px-6 py-4 text-slate-400 text-xs font-semibold">
                        {formatDate(site.createdAt)}
                      </td>
                      <td className="px-6 py-4 text-right">
                        {/* High-contrast Segmented Action Button Group */}
                        <div className="inline-flex rounded-lg border border-slate-200 bg-white overflow-hidden shadow-sm align-middle">
                          <button
                            onClick={() => handleAutoLogin(site.id)}
                            disabled={loginLoading !== null}
                            className="h-8.5 px-3.5 text-xs font-bold flex items-center gap-1 transition-colors border-r border-slate-200 cursor-pointer"
                          >
                            {loginLoading === site.id ? (
                              <Loader className="h-3.5 w-3.5 animate-spin" />
                            ) : (
                              <Zap className="h-3.5 w-3.5 text-yellow-300 fill-yellow-300" />
                            )}
                            Auto Login
                          </button>

                          <Link
                            href={`/websites/${site.id}`}
                            className="h-8.5 px-3 flex items-center gap-1 text-xs font-bold text-slate-700 hover:bg-slate-50 border-r border-slate-200 transition-colors"
                          >
                            <ViewIcon className="h-3.5 w-3.5 text-slate-400" />
                            Details
                          </Link>

                          <button
                            onClick={() => handleDeleteWebsite(site.id)}
                            className="h-8.5 px-3 flex items-center gap-1 text-xs font-bold text-red-600 hover:bg-red-50 transition-colors cursor-pointer"
                          >
                            <Trash2 className="h-3.5 w-3.5 text-red-400" />
                            Delete
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Table Pagination Footer */}
          {totalPages > 1 && (
            <div className="px-6 py-4 border-t border-slate-200 bg-slate-50/50 flex flex-col sm:flex-row items-center justify-between gap-4 text-xs font-semibold text-slate-500">
              <p>
                Showing{" "}
                <span className="text-slate-800">{indexOfFirstItem + 1}</span>{" "}
                to{" "}
                <span className="text-slate-800">
                  {Math.min(indexOfLastItem, websites.length)}
                </span>{" "}
                of <span className="text-slate-800">{websites.length}</span>{" "}
                websites
              </p>

              <div className="flex items-center gap-1.5">
                <button
                  onClick={handlePrevPage}
                  disabled={currentPage === 1}
                  className="p-1.5 rounded-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:hover:bg-white transition-colors cursor-pointer"
                >
                  <ChevronLeft className="h-4 w-4" />
                </button>

                <div className="flex items-center gap-1">
                  {Array.from({ length: totalPages }, (_, i) => i + 1).map(
                    (page) => (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`px-3 py-1.5 rounded-lg border text-xs font-bold transition-all cursor-pointer ${
                          currentPage === page
                            ? "bg-slate-900 border-slate-900 text-white"
                            : "bg-white border-slate-200 text-slate-600 hover:bg-slate-50"
                        }`}
                      >
                        {page}
                      </button>
                    ),
                  )}
                </div>

                <button
                  onClick={handleNextPage}
                  disabled={currentPage === totalPages}
                  className="p-1.5 rounded-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:hover:bg-white transition-colors cursor-pointer"
                >
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* ADD WEBSITE DIALOG MODAL */}
      {modalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-sm animate-fadeIn">
          <div className="w-full max-w-md bg-white border border-slate-200 rounded-2xl shadow-xl p-6 md:p-8 relative">
            <button
              onClick={() => setModalOpen(false)}
              className="absolute top-4 right-4 p-1.5 rounded-lg text-slate-400 hover:text-slate-650 bg-slate-50 hover:bg-slate-100 transition-colors"
            >
              <Plus className="h-5 w-5 rotate-45" />
            </button>

            {/* Error Message banner */}
            {error && (
              <div className="mb-6 p-4 rounded-xl bg-red-50 border border-red-155 text-xs text-red-655 font-semibold">
                {error}
              </div>
            )}

            <form onSubmit={handleAddWebsite} className="space-y-6">
              <div>
                <h3 className="text-xl font-bold text-slate-900 flex items-center gap-2">
                  <Globe className="h-5 w-5 text-blue-600" /> Connect Website
                </h3>
                <p className="text-xs text-slate-500 mt-1">
                  Connect your WordPress website securely using native
                  Application Passwords.
                </p>
              </div>

              <div className="space-y-4">
                <div>
                  <label
                    htmlFor="siteUrl"
                    className="block text-xs font-bold text-slate-400 mb-1.5 uppercase tracking-wider"
                  >
                    WordPress Site URL
                  </label>
                  <input
                    id="siteUrl"
                    type="text"
                    required
                    placeholder="e.g. mywordpresssite.com or https://mysite.com"
                    className="glass-input w-full py-2.5 px-4 rounded-xl text-sm"
                    value={siteUrl}
                    onChange={(e) => setSiteUrl(e.target.value)}
                  />
                  <p className="text-[10px] text-slate-400 mt-1 font-semibold">
                    Ensure your WordPress supports Application Passwords
                    (WordPress 5.6+).
                  </p>
                </div>

                <div>
                  <label
                    htmlFor="siteName"
                    className="block text-xs font-bold text-slate-400 mb-1.5 uppercase tracking-wider"
                  >
                    Site Label (Optional)
                  </label>
                  <input
                    id="siteName"
                    type="text"
                    placeholder="e.g. Personal Blog"
                    className="glass-input w-full py-2.5 px-4 rounded-xl text-sm"
                    value={siteName}
                    onChange={(e) => setSiteName(e.target.value)}
                  />
                </div>
              </div>

              {/* Informational Guidance box */}
              <div className="p-4 rounded-xl bg-blue-50/50 border border-blue-100 text-xs text-slate-650 leading-relaxed font-semibold">
                💡 **Seamless SSO Setup**: You will be redirected to your
                WordPress dashboard to authorize connection. Once approved, the
                RemotePress Must-Use (MU) plugin will be automatically installed
                in the background!
              </div>

              <div className="flex justify-end gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setModalOpen(false)}
                  className="px-4 py-2 text-sm font-semibold text-slate-400 hover:text-slate-650"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting || !siteUrl}
                  className="px-5 py-2.5 text-sm font-bold text-white bg-slate-900 rounded-xl hover:bg-slate-800 disabled:opacity-50 flex items-center gap-1.5 cursor-pointer"
                >
                  {submitting ? (
                    <>
                      <Loader className="h-4.5 w-4.5 animate-spin" />{" "}
                      Redirecting...
                    </>
                  ) : (
                    <>
                      Connect via WordPress <ArrowRight className="h-4 w-4" />
                    </>
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
