"use client";

import { useEffect, useState, use } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  Globe,
  Shield,
  Key,
  Eye,
  EyeOff,
  Loader,
  Trash2,
  ExternalLink,
  Sparkles,
  CheckCircle2,
  Copy,
  Download,
  Zap,
  Terminal,
  Calendar,
  User,
  Settings,
  RefreshCw,
  Lock,
  Plug,
  Palette,
  Cloud,
  Inbox,
  AlertCircle,
  ArrowUpRight,
  FileText,
  Search,
  Plus,
} 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;
    wp_version?: string;
    php_version?: string;
    active_theme?: string;
    active_plugins_count?: string;
    plugin_updates_count?: string;
    high_risk_updates_count?: string;
    theme_has_update?: string;
    website_notes?: string;
  };
}

export default function SiteDetailsPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const router = useRouter();
  const { id } = use(params);

  const [site, setSite] = useState<Website | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [loginLoading, setLoginLoading] = useState(false);
  const [copiedKey, setCopiedKey] = useState(false);
  const [activeTab, setActiveTab] = useState<"general" | "settings">("general");
  const [toast, setToast] = useState<{
    message: string;
    type: "success" | "error" | "info";
  } | null>(null);
  const [testingConnection, setTestingConnection] = useState(false);

  interface WebsiteNoteItem {
    id: string;
    label: string;
    content: string;
    addedBy: string;
    addedOn: string;
  }

  const [notesList, setNotesList] = useState<WebsiteNoteItem[]>([]);
  const [newNoteLabel, setNewNoteLabel] = useState("");
  const [newNoteContent, setNewNoteContent] = useState("");
  const [showAddForm, setShowAddForm] = useState(false);
  const [savingNotes, setSavingNotes] = useState(false);
  const [deletingNoteId, setDeletingNoteId] = useState<string | null>(null);

  const [noteSearchQuery, setNoteSearchQuery] = useState("");
  const [noteCurrentPage, setNoteCurrentPage] = useState(1);
  const noteItemsPerPage = 5;
  const [activeViewNote, setActiveViewNote] = useState<WebsiteNoteItem | null>(
    null,
  );

  useEffect(() => {
    setNoteCurrentPage(1);
  }, [noteSearchQuery]);

  const showToast = (
    message: string,
    type: "success" | "error" | "info" = "success",
  ) => {
    setToast({ message, type });
    // Auto remove after 4 seconds
    const timer = setTimeout(() => setToast(null), 4000);
    return () => clearTimeout(timer);
  };

  useEffect(() => {
    fetchSiteDetails();
  }, [id]);

  useEffect(() => {
    if (site?.metadata?.website_notes) {
      try {
        const parsed = JSON.parse(site.metadata.website_notes);
        if (Array.isArray(parsed)) {
          setNotesList(parsed);
        } else {
          setNotesList([
            {
              id: "legacy",
              label: "General Note",
              content: String(parsed),
              addedBy: "System",
              addedOn: site.createdAt || new Date().toISOString(),
            },
          ]);
        }
      } catch (e) {
        setNotesList([
          {
            id: "legacy",
            label: "General Note",
            content: site.metadata.website_notes,
            addedBy: "System",
            addedOn: site.createdAt || new Date().toISOString(),
          },
        ]);
      }
    } else {
      setNotesList([]);
    }
  }, [site]);

  const fetchSiteDetails = async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetch(`/api/websites/${id}`);
      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Failed to load website details.");
      }

      setSite(data.website);
    } catch (err: any) {
      setError(
        err.message || "Something went wrong while loading site details.",
      );
    } finally {
      setLoading(false);
    }
  };

  const handleTestConnection = async () => {
    if (!site) return;
    try {
      setTestingConnection(true);

      // Step 1: Verification & Environment Stats
      showToast("Step 1/4: Checking remote host connection...", "info");
      const res1 = await fetch(`/api/websites/${site.id}/test-connection`, {
        method: "POST",
      });
      const data1 = await res1.json();

      if (!res1.ok || !data1.success) {
        showToast(
          data1.message ||
            data1.error ||
            "Step 1: Connection verification failed.",
          "error",
        );
        fetchSiteDetails();
        return;
      }

      // Step 2: Settings Sync
      showToast("Step 2/4: Synchronizing WordPress settings...", "info");
      const res2 = await fetch(`/api/websites/${site.id}/sync`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ step: "settings" }),
      });
      const data2 = await res2.json();

      if (!res2.ok || !data2.success) {
        showToast(
          data2.error || "Step 2: Settings synchronization failed.",
          "error",
        );
        fetchSiteDetails();
        return;
      }

      // Step 3: Plugins Sync
      showToast("Step 3/4: Fetching remote plugins list...", "info");
      const res3 = await fetch(`/api/websites/${site.id}/sync`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ step: "plugins" }),
      });
      const data3 = await res3.json();

      if (!res3.ok || !data3.success) {
        showToast(
          data3.error || "Step 3: Plugins list synchronization failed.",
          "error",
        );
        fetchSiteDetails();
        return;
      }

      // Step 4: Theme Sync
      showToast("Step 4/4: Retrieving active theme configuration...", "info");
      const res4 = await fetch(`/api/websites/${site.id}/sync`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ step: "theme" }),
      });
      const data4 = await res4.json();

      if (!res4.ok || !data4.success) {
        showToast(
          data4.error || "Step 4: Active theme synchronization failed.",
          "error",
        );
        fetchSiteDetails();
        return;
      }

      // Complete Success!
      showToast("WordPress site sync fully completed!", "success");
      fetchSiteDetails();
    } catch (err: any) {
      showToast("Network error occurred during multi-step sync.", "error");
    } finally {
      setTestingConnection(false);
    }
  };

  const handleSaveNotes = async () => {
    if (!site) return;
    if (!newNoteLabel.trim() || !newNoteContent.trim()) {
      showToast("Label and Content are required.", "error");
      return;
    }

    try {
      setSavingNotes(true);
      const res = await fetch(`/api/websites/${site.id}/notes`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          label: newNoteLabel.trim(),
          content: newNoteContent.trim(),
        }),
      });
      const data = await res.json();
      if (res.ok && data.success) {
        showToast("Note added successfully!", "success");
        setNewNoteLabel("");
        setNewNoteContent("");
        setShowAddForm(false);
        setSite((prev) => {
          if (!prev) return null;
          return {
            ...prev,
            metadata: {
              ...prev.metadata,
              website_notes: JSON.stringify(data.notes),
            },
          };
        });
      } else {
        showToast(data.error || "Failed to save note.", "error");
      }
    } catch (err: any) {
      showToast("Network error occurred saving note.", "error");
    } finally {
      setSavingNotes(false);
    }
  };

  const handleDeleteNote = async (noteId: string) => {
    if (!site) return;
    if (!confirm("Are you sure you want to delete this note?")) return;

    try {
      setDeletingNoteId(noteId);
      const res = await fetch(
        `/api/websites/${site.id}/notes?noteId=${noteId}`,
        {
          method: "DELETE",
        },
      );
      const data = await res.json();
      if (res.ok && data.success) {
        showToast("Note deleted successfully!", "success");
        setSite((prev) => {
          if (!prev) return null;
          return {
            ...prev,
            metadata: {
              ...prev.metadata,
              website_notes: JSON.stringify(data.notes),
            },
          };
        });
      } else {
        showToast(data.error || "Failed to delete note.", "error");
      }
    } catch (err: any) {
      showToast("Network error occurred deleting note.", "error");
    } finally {
      setDeletingNoteId(null);
    }
  };

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

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

      if (res.ok) {
        router.push("/websites");
      } else {
        const data = await res.json();
        alert(data.error || "Failed to delete site.");
      }
    } catch (err) {
      console.error("Error deleting site:", err);
    }
  };

  const handleAutoLogin = async () => {
    if (!site) return;
    try {
      setLoginLoading(true);
      const res = await fetch(`/api/websites/${site.id}/login-token`, {
        method: "POST",
      });

      const data = await res.json();

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

      window.open(data.redirectUrl, "_blank");
    } catch (err: any) {
      alert(err.message || "Auto Login failed.");
    } finally {
      setLoginLoading(false);
    }
  };

  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: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-24 space-y-3">
        <Loader className="h-8 w-8 text-blue-600 animate-spin" />
        <span className="text-sm font-semibold text-slate-500 animate-pulse">
          Loading website configurations...
        </span>
      </div>
    );
  }

  if (error || !site) {
    return (
      <div className="glass-panel p-8 rounded-2xl text-center max-w-md mx-auto border border-slate-200 bg-white shadow-sm mt-12">
        <div className="w-12 h-12 rounded-full bg-red-50 flex items-center justify-center mx-auto mb-4 border border-red-100">
          <Shield className="h-6 w-6 text-red-500" />
        </div>
        <h3 className="text-lg font-bold text-slate-800 mb-2">
          Error Loading Site
        </h3>
        <p className="text-sm text-slate-500 mb-6 leading-relaxed">
          {error || "The website configuration could not be resolved."}
        </p>
        <Link
          href="/websites"
          className="px-5 py-2.5 rounded-xl bg-slate-100 hover:bg-slate-200 font-semibold text-xs text-slate-700 transition-all"
        >
          Return to Websites
        </Link>
      </div>
    );
  }

  // Determine Connection status badge mapped strictly to Connected / Disconnected / Disabled
  let statusBadge = (
    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs 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>
  );

  if (site.metadata.connection_status === "disabled") {
    statusBadge = (
      <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold bg-slate-100 text-slate-650 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-3 py-1 rounded-full text-xs 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-3 py-1 rounded-full text-xs 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>
    );
  }

  // Auth Method Text
  const authMethodLabel =
    site.authMethod === "plugin_api_key"
      ? "RemotePress Client Plugin"
      : site.authMethod === "application_password"
        ? "WP Application Password"
        : "WP Administrator Credentials";

  // Dynamic WordPress stats for Site Summary (Mockups & Active Connection defaults)
  const wpVersion = site?.metadata?.wp_version || "7.0";
  const phpVersion = site?.metadata?.php_version || "8.2.29";
  const activePlugins = site?.metadata?.active_plugins_count || "0";
  const activeTheme = site?.metadata?.active_theme || "Twenty Twenty-Five";
  const pluginUpdates = parseInt(
    site?.metadata?.plugin_updates_count || "0",
    10,
  );
  const highRiskUpdates = parseInt(
    site?.metadata?.high_risk_updates_count || "0",
    10,
  );
  const themeHasUpdate = site?.metadata?.theme_has_update === "yes";

  // Filtered Notes based on search query
  const filteredNotes = notesList.filter((note) => {
    const query = noteSearchQuery.toLowerCase().trim();
    if (!query) return true;
    return (
      note.label.toLowerCase().includes(query) ||
      note.addedBy.toLowerCase().includes(query)
    );
  });

  // Notes pagination variables
  const indexOfLastNote = noteCurrentPage * noteItemsPerPage;
  const indexOfFirstNote = indexOfLastNote - noteItemsPerPage;
  const currentNotes = filteredNotes.slice(indexOfFirstNote, indexOfLastNote);
  const totalNotePages =
    Math.ceil(filteredNotes.length / noteItemsPerPage) || 1;

  return (
    <div className="space-y-6">
      {/* Site Header details with single line navigation */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-slate-100 pb-5">
        <div className="flex items-center gap-3">
          <Link
            href="/websites"
            className="h-10 w-10 flex items-center justify-center rounded-xl border border-slate-200 bg-white hover:bg-slate-50 hover:border-slate-300 text-slate-500 hover:text-slate-800 transition-all cursor-pointer shadow-sm group shrink-0"
            title="Back to Websites"
          >
            <ArrowLeft className="h-5 w-5 transition-transform group-hover:-translate-x-0.5" />
          </Link>

          <h1 className="text-3xl font-extrabold text-slate-900 tracking-tight">
            {site.siteName}
          </h1>

          <a
            href={site.siteUrl}
            target="_blank"
            className="text-slate-400 hover:text-blue-600 transition-colors inline-flex items-center justify-center p-1"
            title="Visit Website"
          >
            <ExternalLink className="h-5 w-5" />
          </a>
        </div>

        {/* Top Right Actions: Test Connection Reload Icon + Auto Login + Status Badge */}
        <div className="flex items-center gap-3">
          {statusBadge}

          <button
            type="button"
            onClick={handleTestConnection}
            disabled={testingConnection || loginLoading}
            className="h-10 w-10 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 transition-colors disabled:opacity-50 cursor-pointer shadow-sm"
            title="Test Connection"
          >
            <RefreshCw
              className={`h-4 w-4 text-slate-500 ${testingConnection ? "animate-spin" : ""}`}
            />
          </button>

          <button
            onClick={handleAutoLogin}
            disabled={loginLoading || testingConnection}
            className="h-10 px-4 font-bold text-xs rounded-lg bg-slate-900 hover:bg-slate-800 text-white flex items-center gap-1.5 transition-colors disabled:opacity-50 cursor-pointer shadow-sm"
          >
            {loginLoading ? (
              <Loader className="h-3.5 w-3.5 animate-spin" />
            ) : (
              <Zap className="h-3.5 w-3.5 text-yellow-300 fill-yellow-300 animate-pulse" />
            )}
            Auto Login
          </button>
        </div>
      </div>

      {/* Shadcn UI Radix-Style Tabs Switcher */}
      <div className="inline-flex h-10 items-center justify-center rounded-xl bg-slate-100 p-1 text-slate-500">
        <button
          onClick={() => setActiveTab("general")}
          className={`inline-flex items-center justify-center whitespace-nowrap rounded-lg px-4 py-1.5 text-xs font-bold transition-all cursor-pointer ${
            activeTab === "general"
              ? "bg-white text-slate-900 shadow-sm"
              : "text-slate-500 hover:text-slate-800"
          }`}
        >
          General
        </button>
        <button
          onClick={() => setActiveTab("settings")}
          className={`inline-flex items-center justify-center whitespace-nowrap rounded-lg px-4 py-1.5 text-xs font-bold transition-all cursor-pointer ${
            activeTab === "settings"
              ? "bg-white text-slate-900 shadow-sm"
              : "text-slate-500 hover:text-slate-800"
          }`}
        >
          Settings
        </button>
      </div>

      {/* Tab Panels Layout */}
      {activeTab === "general" ? (
        <div className="grid grid-cols-1 md:grid-cols-12 gap-6 items-start">
          {/* Left Column: Metrics & Alerts */}
          <div className="md:col-span-7 space-y-6">
            {/* ENVIRONMENT STATS GRID */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {/* Card 1: WordPress & PHP core environment details */}
              <div className="bg-white border border-slate-200 p-5 rounded-2xl shadow-sm hover:border-slate-300 transition-all flex flex-col justify-between h-full">
                <div className="flex items-center justify-between">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                    Environment
                  </span>
                  <div className="flex gap-1.5">
                    <span className="h-6 w-6 rounded-md bg-blue-50 border border-blue-100 flex items-center justify-center text-blue-600 font-extrabold text-[10px] shrink-0">
                      W
                    </span>
                    <span className="h-6 w-6 rounded-md bg-emerald-50 border border-emerald-100 flex items-center justify-center text-emerald-600 font-mono text-[9px] font-bold shrink-0">
                      php
                    </span>
                  </div>
                </div>
                <div className="space-y-2 mt-4">
                  <div className="flex items-center justify-between border-b border-slate-50 pb-1.5">
                    <span className="text-xs font-semibold text-slate-400">
                      WordPress
                    </span>
                    <span className="text-xs font-extrabold text-slate-700">
                      {wpVersion}
                    </span>
                  </div>
                  <div className="flex items-center justify-between pt-0.5">
                    <span className="text-xs font-semibold text-slate-400">
                      PHP Version
                    </span>
                    <span className="text-xs font-extrabold text-slate-700">
                      {phpVersion}
                    </span>
                  </div>
                </div>
              </div>

              {/* Card 2: Active Plugins updates details */}
              <div className="bg-white border border-slate-200 p-5 rounded-2xl shadow-sm hover:border-slate-300 transition-all flex flex-col justify-between h-full">
                <div className="flex items-center justify-between">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                    Plugins Status
                  </span>
                  <span className="h-7 w-7 rounded-lg bg-purple-50 border border-purple-100 flex items-center justify-center text-purple-600">
                    <Plug className="h-4 w-4" />
                  </span>
                </div>
                <div className="space-y-2 mt-4">
                  <h4 className="text-lg font-extrabold text-slate-800 tracking-tight">
                    {activePlugins} Active
                  </h4>
                  {pluginUpdates > 0 ? (
                    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[10px] font-bold bg-amber-50 text-amber-700 border border-amber-200">
                      <span className="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse" />{" "}
                      {pluginUpdates}{" "}
                      {pluginUpdates === 1 ? "plugin update" : "plugin updates"}{" "}
                      available
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[10px] 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" />{" "}
                      No update available
                    </span>
                  )}
                </div>
              </div>

              {/* Card 3: Active Theme updates details */}
              <div className="bg-white border border-slate-200 p-5 rounded-2xl shadow-sm hover:border-slate-300 transition-all flex flex-col justify-between h-full">
                <div className="flex items-center justify-between">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                    Active Theme
                  </span>
                  <span className="h-7 w-7 rounded-lg bg-orange-50 border border-orange-100 flex items-center justify-center text-orange-600">
                    <Palette className="h-4 w-4" />
                  </span>
                </div>
                <div className="space-y-2 overflow-hidden mt-4">
                  <h4
                    className="text-sm font-extrabold text-slate-800 tracking-tight truncate block max-w-full"
                    title={activeTheme}
                  >
                    {activeTheme}
                  </h4>
                  {themeHasUpdate ? (
                    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[10px] font-bold bg-amber-50 text-amber-700 border border-amber-200">
                      <span className="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse" />{" "}
                      Update available
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[10px] 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" />{" "}
                      No update available
                    </span>
                  )}
                </div>
              </div>
            </div>

            {/* DYNAMIC ALERT CARDS */}
            {pluginUpdates > 0 && (
              <div className="p-4 rounded-2xl border border-amber-150 bg-amber-50/30 flex gap-3 max-w-4xl shadow-sm items-center">
                <div className="h-9 w-9 rounded-xl bg-amber-100 border border-amber-200 flex items-center justify-center text-amber-700 shrink-0 shadow-sm">
                  <Download className="h-4.5 w-4.5" />
                </div>
                <div className="space-y-0.5">
                  <h4 className="text-sm font-bold text-slate-800">
                    {pluginUpdates} Plugin Updates Available
                  </h4>
                  <p className="text-xs text-slate-500 font-semibold">
                    {pluginUpdates} remote plugins have newer versions
                    available. Update them in your WordPress panel.
                  </p>
                </div>
              </div>
            )}

            {highRiskUpdates > 0 && (
              <div className="p-4 rounded-2xl border border-red-150 bg-red-50/20 flex gap-3 max-w-4xl shadow-sm items-center">
                <div className="h-9 w-9 rounded-xl bg-red-100 border border-red-200 flex items-center justify-center text-red-600 shrink-0 shadow-sm">
                  <AlertCircle className="h-4.5 w-4.5 animate-pulse" />
                </div>
                <div className="space-y-0.5">
                  <h4 className="text-sm font-bold text-slate-800">
                    High Risk Updates Detected
                  </h4>
                  <p className="text-xs text-slate-500 font-semibold">
                    {highRiskUpdates} remote plugin updates are marked as high
                    risk. Review details before upgrading.
                  </p>
                </div>
              </div>
            )}
          </div>

          {/* Right Column: Platform Notes Card */}
          <div className="md:col-span-5">
            <div className="glass-panel p-5 rounded-2xl border border-slate-50 bg-white shadow-sm flex flex-col space-y-4 min-h-[350px]">
              <div className="flex items-center justify-between border-b border-slate-100 pb-2.5">
                <div className="space-y-0.5">
                  <h3 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                    <FileText className="h-4.5 w-4.5 text-blue-600" /> Website
                    Notes
                  </h3>
                  <p className="text-[10px] text-slate-400 font-medium">
                    Platform-only secure notes.
                  </p>
                </div>
                {!showAddForm && (
                  <button
                    onClick={() => setShowAddForm(true)}
                    className="h-7 px-2.5 font-bold text-[10px] rounded-lg bg-slate-900 hover:bg-slate-800 text-white flex items-center gap-1 transition-colors cursor-pointer shadow-sm"
                  >
                    + Add Note
                  </button>
                )}
              </div>

              {/* Note Add Form / Notes Table Display */}
              {showAddForm ? (
                <div className="space-y-3.5 p-3.5 rounded-xl border border-slate-100 bg-slate-50/50 animate-fadeIn">
                  <span className="block text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                    Create New Note
                  </span>

                  <div className="space-y-2">
                    <input
                      type="text"
                      placeholder="Note Label (e.g. SFTP Access)"
                      value={newNoteLabel}
                      onChange={(e) => setNewNoteLabel(e.target.value)}
                      className="w-full px-3 py-2 rounded-lg border border-slate-200 text-xs focus:ring-1 focus:ring-slate-900 focus:border-slate-900 bg-white outline-none font-semibold text-slate-850 placeholder-slate-400"
                    />

                    <textarea
                      placeholder="Enter note contents here..."
                      value={newNoteContent}
                      onChange={(e) => setNewNoteContent(e.target.value)}
                      className="w-full min-h-[100px] p-3 rounded-lg border border-slate-200 text-xs focus:ring-1 focus:ring-slate-900 focus:border-slate-900 bg-white outline-none resize-none font-medium text-slate-700 placeholder-slate-400 leading-normal"
                    />
                  </div>

                  <div className="flex justify-end gap-2 pt-1">
                    <button
                      type="button"
                      onClick={() => {
                        setShowAddForm(false);
                        setNewNoteLabel("");
                        setNewNoteContent("");
                      }}
                      className="h-8 px-3 font-bold text-xs rounded-lg text-slate-400 hover:text-slate-650 hover:bg-slate-100 transition-colors"
                    >
                      Cancel
                    </button>
                    <button
                      type="button"
                      onClick={handleSaveNotes}
                      disabled={
                        savingNotes ||
                        !newNoteLabel.trim() ||
                        !newNoteContent.trim()
                      }
                      className="h-8 px-3.5 font-bold text-xs rounded-lg bg-slate-900 hover:bg-slate-800 text-white flex items-center gap-1 transition-colors disabled:opacity-50 cursor-pointer shadow-sm"
                    >
                      {savingNotes ? (
                        <>
                          <Loader className="h-3 w-3 animate-spin" /> Saving...
                        </>
                      ) : (
                        "Save Note"
                      )}
                    </button>
                  </div>
                </div>
              ) : notesList.length === 0 ? (
                <div className="flex-grow flex flex-col items-center justify-center py-10 text-center border-2 border-dashed border-slate-100 rounded-xl">
                  <FileText className="h-8 w-8 text-slate-300 mb-2" />
                  <p className="text-xs font-bold text-slate-400">
                    No notes recorded yet
                  </p>
                  <p className="text-[10px] text-slate-400 px-4 mt-0.5 font-medium leading-normal">
                    Create secure credentials or deployment checklist details
                    local to this website.
                  </p>
                </div>
              ) : (
                <div className="flex flex-col space-y-3 flex-grow">
                  {/* Real-time Search input */}
                  <div className="relative">
                    <Search className="absolute left-3 top-2.5 h-3.5 w-3.5 text-slate-400" />
                    <input
                      type="text"
                      placeholder="Search notes..."
                      value={noteSearchQuery}
                      onChange={(e) => setNoteSearchQuery(e.target.value)}
                      className="w-full pl-9 pr-4 py-2 rounded-xl border border-slate-100 text-xs focus:ring-1 focus:ring-slate-200 focus:border-slate-200 bg-slate-50/30 outline-none font-semibold text-slate-700 placeholder-slate-400 transition-all"
                    />
                  </div>

                  {filteredNotes.length === 0 ? (
                    <div className="flex-grow flex flex-col items-center justify-center py-8 text-center border border-dashed border-slate-100 rounded-xl bg-slate-50/30">
                      <Search className="h-6 w-6 text-slate-300 mb-1.5" />
                      <p className="text-xs font-bold text-slate-400">
                        No matching notes found
                      </p>
                      <p className="text-[10px] text-slate-400 px-4 mt-0.5 font-medium leading-normal">
                        Try refining your search query.
                      </p>
                    </div>
                  ) : (
                    <div className="flex-grow flex flex-col justify-between space-y-3 animate-fadeIn">
                      <div className="overflow-hidden border border-slate-100 rounded-xl bg-white shadow-sm">
                        <table className="w-full text-left border-collapse text-[11px]">
                          <thead>
                            <tr className="border-b border-slate-100 bg-slate-50 text-slate-400 font-bold uppercase tracking-wider text-[9px]">
                              <th className="px-3 py-2 font-bold">Label</th>
                              <th className="px-3 py-2 font-bold">Added By</th>
                              <th className="px-3 py-2 font-bold">Added On</th>
                              <th className="px-3 py-2 font-bold text-right">
                                Actions
                              </th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-slate-100 text-slate-750 bg-white">
                            {currentNotes.map((note) => (
                              <tr
                                key={note.id}
                                className="hover:bg-slate-50/50 transition-colors group"
                              >
                                <td
                                  className="px-3 py-2 font-bold text-slate-800 max-w-[90px] truncate"
                                  title={note.label}
                                >
                                  {note.label}
                                </td>
                                <td
                                  className="px-3 py-2 text-slate-550 font-bold max-w-[80px] truncate"
                                  title={note.addedBy}
                                >
                                  {note.addedBy}
                                </td>
                                <td className="px-3 py-2 text-slate-400 font-bold">
                                  {new Date(note.addedOn).toLocaleDateString(
                                    undefined,
                                    { month: "short", day: "numeric" },
                                  )}
                                </td>
                                <td className="px-3 py-2 text-right">
                                  <div className="inline-flex gap-1.5 justify-end w-full">
                                    <button
                                      type="button"
                                      onClick={() => setActiveViewNote(note)}
                                      className="text-slate-400 hover:text-blue-600 transition-colors p-1 rounded hover:bg-slate-100 cursor-pointer"
                                      title="View Details"
                                    >
                                      <Eye className="h-3.5 w-3.5" />
                                    </button>
                                    <button
                                      type="button"
                                      onClick={() => handleDeleteNote(note.id)}
                                      disabled={deletingNoteId === note.id}
                                      className="text-slate-400 hover:text-red-500 transition-colors p-1 rounded hover:bg-slate-100 disabled:opacity-50 cursor-pointer"
                                      title="Delete Note"
                                    >
                                      {deletingNoteId === note.id ? (
                                        <Loader className="h-3.5 w-3.5 animate-spin" />
                                      ) : (
                                        <Trash2 className="h-3.5 w-3.5" />
                                      )}
                                    </button>
                                  </div>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>

                      {/* Pagination Footer */}
                      {totalNotePages > 1 && (
                        <div className="flex items-center justify-between text-[10px] font-bold text-slate-450 pt-2 border-t border-slate-100">
                          <span>
                            Showing {indexOfFirstNote + 1}-
                            {Math.min(indexOfLastNote, filteredNotes.length)} of{" "}
                            {filteredNotes.length} notes
                          </span>
                          <div className="flex items-center gap-1.5">
                            <button
                              type="button"
                              onClick={() =>
                                setNoteCurrentPage((prev) =>
                                  Math.max(prev - 1, 1),
                                )
                              }
                              disabled={noteCurrentPage === 1}
                              className="px-2 py-1 rounded border border-slate-200 bg-white hover:bg-slate-50 disabled:opacity-40 disabled:hover:bg-white text-slate-600 font-bold transition-colors cursor-pointer text-[9px]"
                            >
                              Prev
                            </button>
                            <button
                              type="button"
                              onClick={() =>
                                setNoteCurrentPage((prev) =>
                                  Math.min(prev + 1, totalNotePages),
                                )
                              }
                              disabled={noteCurrentPage === totalNotePages}
                              className="px-2 py-1 rounded border border-slate-200 bg-white hover:bg-slate-50 disabled:opacity-40 disabled:hover:bg-white text-slate-600 font-bold transition-colors cursor-pointer text-[9px]"
                            >
                              Next
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-12 gap-6 items-start">
          <div className="md:col-span-8 space-y-6">
            {/* Connection Card under Settings */}
            <div className="glass-panel p-6 rounded-2xl border border-slate-200 bg-white shadow-sm space-y-4">
              <h3 className="text-md font-bold text-slate-900 flex items-center gap-2 border-b border-slate-50 pb-3">
                <Globe className="h-4.5 w-4.5 text-blue-600" /> Connection
                Configuration
              </h3>

              <div className="space-y-4 text-sm">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <span className="text-xs font-bold text-slate-400 uppercase tracking-wide block">
                      WordPress Endpoint URL
                    </span>
                    <a
                      href={site.siteUrl}
                      target="_blank"
                      className="font-semibold text-blue-600 hover:underline inline-flex items-center gap-1"
                    >
                      {site.siteUrl} <ExternalLink className="h-3.5 w-3.5" />
                    </a>
                  </div>

                  <div className="space-y-1">
                    <span className="text-xs font-bold text-slate-400 uppercase tracking-wide block">
                      Auth Protocol
                    </span>
                    <span className="font-semibold text-slate-700">
                      {authMethodLabel}
                    </span>
                  </div>
                </div>

                {/* Test Connection Button inside Settings */}
                <div className="flex items-center gap-3 pt-2">
                  <span className="text-xs text-slate-500 font-bold">
                    Refresh Connection:
                  </span>
                  <button
                    type="button"
                    onClick={handleTestConnection}
                    disabled={testingConnection}
                    className="h-10 w-10 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-slate-750 transition-all cursor-pointer shadow-sm"
                    title="Test Connection"
                  >
                    <RefreshCw
                      className={`h-4 w-4 text-slate-500 ${testingConnection ? "animate-spin" : ""}`}
                    />
                  </button>
                </div>

                {/* If Plugin is active, show API Key and Download trigger inside Settings */}
                {site.authMethod === "plugin_api_key" && (
                  <div className="pt-4 border-t border-slate-100 space-y-4">
                    {site.metadata.api_key && (
                      <div className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
                        <span className="block text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                          Site Connection API Key
                        </span>
                        <div className="flex gap-2">
                          <input
                            type="password"
                            readOnly
                            className="bg-white border border-slate-200 px-3 py-2 rounded-lg text-xs font-mono text-slate-800 flex-1"
                            value={site.metadata.api_key}
                          />
                          <button
                            onClick={() =>
                              copyToClipboard(site.metadata.api_key || "")
                            }
                            className="px-3 rounded-lg bg-white border border-slate-200 hover:bg-slate-100 transition-colors text-slate-650 hover:text-slate-800 flex items-center gap-1 font-semibold text-xs cursor-pointer"
                          >
                            {copiedKey ? (
                              <CheckCircle2 className="h-4 w-4 text-emerald-500" />
                            ) : (
                              <Copy className="h-4 w-4" />
                            )}
                            {copiedKey ? "Copied" : "Copy"}
                          </button>
                        </div>
                      </div>
                    )}

                    <div className="flex items-center gap-3">
                      <a
                        href="/wp-plugin/remotepress.zip"
                        target="_blank"
                        className="px-4 py-2.5 font-bold text-xs rounded-xl bg-slate-50 hover:bg-slate-100 border border-slate-200 hover:border-slate-300 text-slate-700 flex items-center gap-1.5 transition-all text-center"
                      >
                        <Download className="h-4 w-4" /> Download Client Plugin
                        ZIP
                      </a>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Website Configuration Parameters (Moved here) */}
            <div className="glass-panel p-6 rounded-2xl border border-slate-200 bg-white shadow-sm space-y-4">
              <h3 className="text-md font-bold text-slate-900 flex items-center gap-2 border-b border-slate-50 pb-3">
                <Terminal className="h-4.5 w-4.5 text-blue-600" /> Website
                Configuration Parameters
              </h3>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 text-sm">
                <div className="space-y-1">
                  <span className="text-xs font-bold text-slate-400 uppercase tracking-wide block">
                    Authentication Method
                  </span>
                  <span className="font-semibold text-slate-700">
                    {authMethodLabel}
                  </span>
                </div>

                <div className="space-y-1">
                  <span className="text-xs font-bold text-slate-400 uppercase tracking-wide block">
                    Designated WP User
                  </span>
                  <span className="font-semibold text-slate-700 flex items-center gap-1.5">
                    <User className="h-4 w-4 text-slate-400" />{" "}
                    {site.metadata.wp_username || "admin"}
                  </span>
                </div>

                <div className="space-y-1">
                  <span className="text-xs font-bold text-slate-400 uppercase tracking-wide block">
                    Registered On
                  </span>
                  <span className="font-semibold text-slate-700 flex items-center gap-1.5">
                    <Calendar className="h-4 w-4 text-slate-400" />{" "}
                    {formatDate(site.createdAt)}
                  </span>
                </div>

                <div className="space-y-1">
                  <span className="text-xs font-bold text-slate-400 uppercase tracking-wide block">
                    SaaS Connection ID
                  </span>
                  <span className="font-mono text-xs text-slate-500 font-semibold">
                    RP-SITE-{site.id.toString().padStart(4, "0")}
                  </span>
                </div>
              </div>
            </div>

            {/* Setup / Synchronization Guide (Moved here) */}
            <div className="glass-panel p-6 rounded-2xl border border-slate-200 bg-white shadow-sm space-y-4">
              <h3 className="text-md font-bold text-slate-900 flex items-center gap-2 border-b border-slate-50 pb-3">
                <Shield className="h-4.5 w-4.5 text-blue-600" /> Setup &
                Activation Guide
              </h3>

              {site.authMethod === "plugin_api_key" ? (
                <div className="space-y-4 text-slate-600 text-sm leading-relaxed">
                  <p>
                    To sync and authenticate this site using our custom
                    connection protocol, install the client plugin manually:
                  </p>

                  <div className="space-y-3.5 text-xs pl-2">
                    <div className="flex items-start gap-3">
                      <div className="w-5 h-5 rounded-full bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0 font-bold text-blue-600 text-[10px]">
                        1
                      </div>
                      <p className="mt-0.5">
                        Download the packaged plugin ZIP folder and upload it
                        under plugins inside WordPress dashboard.
                      </p>
                    </div>

                    <div className="flex items-start gap-3">
                      <div className="w-5 h-5 rounded-full bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0 font-bold text-blue-600 text-[10px]">
                        2
                      </div>
                      <p className="mt-0.5">
                        Activate the plugin: Go to **Plugins &gt; Installed
                        Plugins** and click **Activate** under **RemotePress**.
                      </p>
                    </div>

                    <div className="flex items-start gap-3">
                      <div className="w-5 h-5 rounded-full bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0 font-bold text-blue-600 text-[10px]">
                        3
                      </div>
                      <p className="mt-0.5">
                        Open the **RemotePress** menu inside your WordPress
                        Settings, paste the API Key and this SaaS URL (
                        <code className="px-1 py-0.5 rounded bg-slate-100 text-blue-600 font-mono">
                          http://localhost:3000
                        </code>
                        ), and save options!
                      </p>
                    </div>
                  </div>

                  <div className="p-4 rounded-xl bg-blue-50 border border-blue-100 text-xs text-blue-800 mt-2">
                    ℹ️ **Handshake Success**: Once the options are saved, the
                    status badge at the top of this details page will instantly
                    transition from **Disconnected** to **Connected**!
                  </div>
                </div>
              ) : site.authMethod === "application_password" ? (
                <div className="space-y-3 text-slate-600 text-sm leading-relaxed">
                  <p>
                    This site is configured to authorize using a native
                    WordPress **Application Password**.
                  </p>
                  <ul className="list-disc pl-5 space-y-1.5 text-xs text-slate-500">
                    <li>
                      Ensure the username `
                      {site.metadata.wp_username || "admin"}` represents an
                      active administrator user in WordPress.
                    </li>
                    <li>
                      Application Passwords can be revoked at any time inside
                      your WordPress profile details page.
                    </li>
                    <li>
                      To switch connection pathways later, delete this
                      connection and choose a different connection option.
                    </li>
                  </ul>
                </div>
              ) : (
                <div className="space-y-3 text-slate-600 text-sm leading-relaxed">
                  <p>
                    This site is configured to authorize using standard
                    WordPress **Admin Credentials** (Username & Password).
                  </p>
                  <ul className="list-disc pl-5 space-y-1.5 text-xs text-slate-500">
                    <li>
                      WordPress credentials allow the SaaS to securely request
                      dashboard sessions in the background.
                    </li>
                    <li>
                      Ensure the password has not been altered on the WordPress
                      site.
                    </li>
                    <li>
                      For maximum security, we recommend using the **RemotePress
                      Client Plugin API Key** connection.
                    </li>
                  </ul>
                </div>
              )}
            </div>
          </div>

          <div className="md:col-span-4 space-y-6">
            {/* Danger Zone & Delete Connection inside Settings */}
            <div className="glass-panel p-6 rounded-2xl border border-red-100 bg-white shadow-sm space-y-4">
              <h3 className="text-md font-bold text-red-650 flex items-center gap-2 border-b border-red-50 pb-3">
                <Trash2 className="h-4.5 w-4.5 text-red-500" /> Danger Zone
              </h3>

              <div className="space-y-4">
                <p className="text-xs text-slate-500 leading-normal">
                  Permanently delete this website connection from RemotePress.
                  All active single-click SSO tokens, synchronization metadata,
                  and verification scopes will be completely erased. This action
                  cannot be undone.
                </p>

                <button
                  onClick={handleDeleteWebsite}
                  className="py-2.5 px-4 font-bold text-xs rounded-xl border border-red-200 hover:bg-red-50 text-red-600 transition-all flex items-center gap-2 cursor-pointer"
                >
                  <Trash2 className="h-4 w-4" /> Delete Site Connection
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* View Note Modal */}
      {activeViewNote && (
        <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 relative animate-scaleIn">
            <button
              onClick={() => setActiveViewNote(null)}
              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 cursor-pointer"
            >
              <Plus className="h-5 w-5 rotate-45" />
            </button>

            <div className="space-y-4">
              <div className="space-y-1">
                <span className="inline-flex px-2 py-0.5 rounded-md text-[10px] font-bold bg-blue-50 text-blue-700 border border-blue-200 uppercase tracking-wider">
                  {activeViewNote.label}
                </span>
                <h3 className="text-lg font-bold text-slate-900 pt-1">
                  Note Details
                </h3>
              </div>

              <div className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
                <div className="flex justify-between items-center">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                    Content
                  </span>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(activeViewNote.content);
                      showToast("Note content copied!", "success");
                    }}
                    className="h-6 px-2 rounded-md bg-white border border-slate-250 hover:bg-slate-100 text-slate-600 hover:text-slate-800 transition-colors flex items-center gap-1 font-bold text-[10px] cursor-pointer"
                  >
                    <Copy className="h-3 w-3" /> Copy
                  </button>
                </div>
                <p className="text-xs font-semibold text-slate-700 whitespace-pre-wrap leading-normal break-words bg-white p-3 rounded-lg border border-slate-100 font-mono select-all">
                  {activeViewNote.content}
                </p>
              </div>

              <div className="border-t border-slate-100 pt-3 flex items-center justify-between text-[10px] text-slate-450 font-bold uppercase tracking-wider">
                <span>By {activeViewNote.addedBy}</span>
                <span>
                  {new Date(activeViewNote.addedOn).toLocaleDateString(
                    undefined,
                    {
                      month: "short",
                      day: "numeric",
                      year: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                    },
                  )}
                </span>
              </div>

              <div className="flex justify-end pt-2">
                <button
                  onClick={() => setActiveViewNote(null)}
                  className="px-4 py-2 font-bold text-xs rounded-xl bg-slate-900 hover:bg-slate-800 text-white transition-colors cursor-pointer shadow-sm"
                >
                  Close Note
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Floating Toast Notification Box */}
      {toast && (
        <div className="fixed bottom-5 right-5 z-50 flex items-center gap-3 px-4 py-3 rounded-xl border border-slate-200 bg-white shadow-lg text-sm max-w-sm transition-all duration-300 animate-slideIn">
          <div
            className={`w-2.5 h-2.5 rounded-full shrink-0 ${
              toast.type === "success"
                ? "bg-emerald-500 animate-pulse"
                : toast.type === "error"
                  ? "bg-red-500 animate-pulse"
                  : "bg-blue-500 animate-pulse"
            }`}
          />
          <span className="font-bold text-slate-800 flex-1">
            {toast.message}
          </span>
          <button
            onClick={() => setToast(null)}
            className="text-slate-400 hover:text-slate-650 font-bold ml-2 text-lg"
          >
            ×
          </button>
        </div>
      )}
    </div>
  );
}
