"use client";

import {
  faArrowDown,
  faArrowUp,
  faPlus,
  faShareAlt,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useState } from "react";
import Toast from "@/components/ui/Toast";
import { useAdminToast } from "@/hooks/admin/useAdminToast";
import type { SocialLink } from "@/types/models";
import AdminPageHeader from "@/components/admin/AdminPageHeader";
import AdminCard from "@/components/admin/AdminCard";
import AdminInput from "@/components/admin/AdminInput";
import AdminSelect from "@/components/admin/AdminSelect";
import AdminEmptyState from "@/components/admin/AdminEmptyState";
import AdminConfirmDialog from "@/components/admin/AdminConfirmDialog";
import AdminFormModal from "@/components/admin/AdminFormModal";
import AdminDataTable from "@/components/admin/AdminDataTable";
import AdminEditDeleteButtons from "@/components/admin/AdminEditDeleteButtons";
import AdminBadge from "@/components/admin/AdminBadge";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";

const SOCIAL_PLATFORMS = [
  {
    value: "twitter",
    label: "Twitter",
    icon: "M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z",
  },
  {
    value: "facebook",
    label: "Facebook",
    icon: "M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z",
  },
  {
    value: "instagram",
    label: "Instagram",
    icon: "M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678c-3.405 0-6.162 2.76-6.162 6.162 0 3.405 2.76 6.162 6.162 6.162 3.405 0 6.162-2.76 6.162-6.162 0-3.405-2.76-6.162-6.162-6.162zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405c0 .795-.646 1.44-1.44 1.44-.795 0-1.44-.646-1.44-1.44 0-.794.646-1.439 1.44-1.439.793-.001 1.44.645 1.44 1.439z",
  },
  {
    value: "linkedin",
    label: "LinkedIn",
    icon: "M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z",
  },
  {
    value: "youtube",
    label: "YouTube",
    icon: "M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z",
  },
  {
    value: "tiktok",
    label: "TikTok",
    icon: "M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z",
  },
];

const defaultForm = {
  platform: "twitter",
  url: "",
  icon: SOCIAL_PLATFORMS[0].icon,
  isActive: true,
};

export default function AdminSocials() {
  const [socialLinks, setSocialLinks] = useState<SocialLink[]>([]);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [formData, setFormData] = useState<Partial<SocialLink>>(defaultForm);
  const [showEditor, setShowEditor] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    id: number | null;
  }>({ isOpen: false, id: null });
  const { toast, showSuccess, showError, hideToast } = useAdminToast();

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

  const fetchSocialLinks = async () => {
    try {
      const response = await fetch("/api/social-links");
      setSocialLinks(await response.json());
    } catch {
      showError("Failed to fetch social links");
    } finally {
      setLoading(false);
    }
  };

  const handlePlatformChange = (platform: string) => {
    const selected = SOCIAL_PLATFORMS.find((p) => p.value === platform);
    setFormData({ ...formData, platform, icon: selected?.icon || "" });
  };

  const resetForm = () => {
    setEditingId(null);
    setFormData(defaultForm);
    setShowEditor(false);
  };

  const handleSubmit = async () => {
    if (!formData.platform || !formData.url || !formData.icon) {
      showError("Please fill in all required fields");
      return;
    }
    setIsSaving(true);
    try {
      const payload = editingId
        ? { id: editingId, ...formData }
        : { ...formData, order: socialLinks.length };
      const response = await adminFetch("/api/social-links", {
        method: editingId ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!response.ok) throw new Error();
      await fetchSocialLinks();
      showSuccess(
        editingId ? "Social link updated successfully!" : "Social link saved successfully!",
      );
      resetForm();
    } catch {
      showError("Failed to save social link");
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await adminFetch("/api/social-links", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });
      if (!response.ok) throw new Error();
      await fetchSocialLinks();
      showSuccess("Social link deleted successfully!");
    } catch {
      showError("Failed to delete social link");
    } finally {
      setDeleteConfirm({ isOpen: false, id: null });
    }
  };

  const startEdit = (link: SocialLink) => {
    setEditingId(link.id!);
    setFormData(link);
    setShowEditor(true);
  };

  const moveLink = async (index: number, direction: number) => {
    const newLinks = [...socialLinks];
    const target = index + direction;
    if (target < 0 || target >= newLinks.length) return;
    [newLinks[index], newLinks[target]] = [newLinks[target], newLinks[index]];
    const updated = newLinks.map((link, i) => ({ ...link, order: i }));
    try {
      await Promise.all(
        updated
          .slice(Math.min(index, target), Math.max(index, target) + 1)
          .map((link) =>
            adminFetch("/api/social-links", {
              method: "PUT",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(link),
            }),
          ),
      );
      await fetchSocialLinks();
    } catch {
      showError("Failed to reorder social links");
    }
  };

  return (
    <>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}

      <AdminConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, id: null })}
        onConfirm={() => deleteConfirm.id && handleDelete(deleteConfirm.id)}
        title="Delete social link"
        message="Are you sure you want to delete this social link? This action cannot be undone."
      />

      <AdminPageHeader
        title="Social Links"
        description="Manage social media links displayed on your website"
        action={{
          label: "Add link",
          onClick: () => {
            setEditingId(null);
            setFormData(defaultForm);
            setShowEditor(true);
          },
          icon: faPlus,
          variant: "primary",
        }}
      />

      <AdminCard padding="none">
        {loading ? (
          <AdminLoadingState message="Loading social links..." />
        ) : socialLinks.length === 0 ? (
          <div className="p-6">
            <AdminEmptyState
              title="No social links yet"
              description="Add your first social media link to get started"
              icon={faShareAlt}
              action={{
                label: "Add link",
                onClick: () => {
                  setEditingId(null);
                  setFormData(defaultForm);
                  setShowEditor(true);
                },
              }}
            />
          </div>
        ) : (
          <AdminDataTable
            items={socialLinks}
            rowKey={(l) => l.id!}
            columns={[
              {
                key: "order",
                header: "Order",
                width: "w-20",
                render: (_, index) => (
                  <div className="flex items-center gap-1">
                    <button
                      type="button"
                      onClick={() => moveLink(index, -1)}
                      disabled={index === 0}
                      className="inline-flex h-6 w-6 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-slate-800 hover:text-slate-100 disabled:cursor-not-allowed disabled:opacity-30"
                      title="Move up"
                      aria-label="Move up"
                    >
                      <FontAwesomeIcon icon={faArrowUp} className="h-3 w-3" />
                    </button>
                    <button
                      type="button"
                      onClick={() => moveLink(index, 1)}
                      disabled={index === socialLinks.length - 1}
                      className="inline-flex h-6 w-6 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-slate-800 hover:text-slate-100 disabled:cursor-not-allowed disabled:opacity-30"
                      title="Move down"
                      aria-label="Move down"
                    >
                      <FontAwesomeIcon icon={faArrowDown} className="h-3 w-3" />
                    </button>
                  </div>
                ),
              },
              {
                key: "platform",
                header: "Platform",
                render: (link) => (
                  <div className="flex items-center gap-2.5">
                    <svg
                      className="h-4 w-4 text-slate-400"
                      fill="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path d={link.icon} />
                    </svg>
                    <span className="font-medium capitalize text-slate-100">
                      {link.platform}
                    </span>
                  </div>
                ),
              },
              {
                key: "url",
                header: "URL",
                render: (link) => (
                  <a
                    href={link.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="truncate text-slate-300 hover:text-indigo-300"
                  >
                    {link.url}
                  </a>
                ),
              },
              {
                key: "status",
                header: "Status",
                render: (link) =>
                  link.isActive ? (
                    <AdminBadge variant="success">Active</AdminBadge>
                  ) : (
                    <AdminBadge variant="neutral">Inactive</AdminBadge>
                  ),
              },
            ]}
            actions={(link) => (
              <AdminEditDeleteButtons
                onEdit={() => startEdit(link)}
                onDelete={() => setDeleteConfirm({ isOpen: true, id: link.id! })}
              />
            )}
          />
        )}
      </AdminCard>

      <AdminFormModal
        isOpen={showEditor}
        onClose={resetForm}
        title={editingId ? "Edit social link" : "Add new social link"}
        onSubmit={handleSubmit}
        isLoading={isSaving}
        submitLabel={editingId ? "Save changes" : "Add link"}
      >
        <AdminSelect
          label="Platform"
          options={SOCIAL_PLATFORMS.map((p) => ({ value: p.value, label: p.label }))}
          value={formData.platform || "twitter"}
          onChange={(e) => handlePlatformChange(e.target.value)}
        />
        <AdminInput
          label="URL"
          type="url"
          placeholder="https://example.com"
          value={formData.url || ""}
          onChange={(e) => setFormData({ ...formData, url: e.target.value })}
          required
        />
        <label className="inline-flex items-center gap-2.5">
          <input
            type="checkbox"
            checked={formData.isActive ?? true}
            onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
            className="h-4 w-4 rounded border-slate-700 bg-slate-900 text-indigo-500 focus:ring-2 focus:ring-indigo-500/60"
          />
          <span className="text-sm font-medium text-slate-300">Active</span>
        </label>
      </AdminFormModal>
    </>
  );
}
