import { useMemo, useState } from "react";
import {
  AlertCircle,
  Filter,
  FileUp,
  HardDrive,
  Layers,
  Loader2,
  Paperclip,
  Pencil,
  Plus,
  Search,
  Settings,
  Trash2,
} from "lucide-react";

// import Breadcrumbs from "@/components/Breadcrumbs";
import EditFileUploadSettingDialog from "./EditFileUploadSettingDialog";
import ManageFileUploadFieldsDialog from "./ManageFileUploadFieldsDialog";
import DeleteFileUploadSettingDialog from "./DeleteFileUploadSettingDialog";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import { getMinFiles } from "@/types/fileUploadSettings";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { useDeleteFileUploadSetting } from "@/hooks/useFileUploadSettings";

export default function FileUploadSettingsPage() {
  const [query, setQuery] = useState("");

  const { data, isLoading, isError, error } = useQuery(
    api.fileUploadSettings.list.queryOptions(),
  );
  const deleteMutation = useDeleteFileUploadSetting();

  const fileUploadSettings = useMemo(
    () => (Array.isArray(data) ? data : []),
    [data],
  );

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return fileUploadSettings;
    return fileUploadSettings.filter(
      (s) =>
        s.code.toLowerCase().includes(q) ||
        s.label.toLowerCase().includes(q) ||
        (s.description ?? "").toLowerCase().includes(q) ||
        s.fields.some(
          (f) =>
            f.fileKey.toLowerCase().includes(q) ||
            f.fileLabel.toLowerCase().includes(q),
        ),
    );
  }, [fileUploadSettings, query]);

  const totalFields = fileUploadSettings.reduce(
    (sum, s) => sum + s.fields.length,
    0,
  );
  const requiredFields = fileUploadSettings.reduce(
    (sum, s) => sum + s.fields.filter((f) => f.isRequired).length,
    0,
  );
  const multiFields = fileUploadSettings.reduce(
    (sum, s) => sum + s.fields.filter((f) => f.isMultiple).length,
    0,
  );

  return (
    <div className="min-h-screen bg-slate-50 p-6">
      <div className="mx-auto max-w-7xl space-y-6">
        <Breadcrumbs
          items={[
            { label: "Admin", href: "/admin" },
            { label: "File Upload Settings" },
          ]}
        />

        {/* Header */}
        <div className="flex flex-col gap-4 rounded-3xl bg-white p-6 shadow-sm md:flex-row md:items-center md:justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight text-slate-900">
              File Upload Settings
            </h1>
            <p className="mt-1 text-sm text-slate-500">
              Define the file inputs every form in the platform should render —
              required/optional, single/multiple, allowed types and size.
            </p>
          </div>

          <div className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center">
            <div className="relative w-full sm:w-80">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
              <input
                type="search"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Search by code, label, or file key..."
                className="h-10 w-full rounded-2xl border border-slate-200 bg-white pl-10 pr-4 text-sm text-slate-700 outline-none transition placeholder:text-slate-400 focus:border-[#10B981]/50 focus:ring-2 focus:ring-[#10B981]/20"
              />
            </div>

            <EditFileUploadSettingDialog mode="create">
              <button
                type="button"
                className="inline-flex w-35 items-center justify-center gap-2 rounded-md bg-[#10B981] px-4 py-2 text-sm font-medium text-white transition hover:bg-[#10B981]/90"
              >
                <Plus className="h-4 w-4" />
                New Setting
              </button>
            </EditFileUploadSettingDialog>
          </div>
        </div>

        {/* Stats */}
        <div className="grid gap-4 md:grid-cols-4">
          <StatCard
            title="Settings"
            value={String(fileUploadSettings.length)}
            icon={<Settings className="h-5 w-5" />}
          />
          <StatCard
            title="Total Fields"
            value={String(totalFields)}
            icon={<Paperclip className="h-5 w-5" />}
          />
          <StatCard
            title="Required"
            value={String(requiredFields)}
            icon={<FileUp className="h-5 w-5" />}
          />
          <StatCard
            title="Multi-file"
            value={String(multiFields)}
            icon={<Layers className="h-5 w-5" />}
          />
        </div>

        {/* Table */}
        <div className="overflow-hidden rounded-3xl bg-white shadow-sm">
          <div className="flex items-center justify-between border-b border-slate-100 px-6 py-4">
            <div>
              <h2 className="text-lg font-semibold text-slate-900">
                Registered File Upload Groups
              </h2>
              <p className="text-sm text-slate-500">
                Every group a form can reference by code.
              </p>
            </div>

            <button className="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 transition hover:border-[#10B981]/30 hover:bg-[#10B981]/10 hover:text-[#10B981]">
              <Filter className="h-4 w-4" />
              Filter
            </button>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full min-w-[1100px] whitespace-nowrap text-left">
              <thead className="bg-slate-50 text-sm text-slate-500">
                <tr>
                  <th className="px-6 py-4 font-medium">Setting</th>
                  <th className="px-6 py-4 font-medium">Code</th>
                  <th className="px-6 py-4 font-medium">Entity</th>
                  <th className="px-6 py-4 font-medium">Fields</th>
                  <th className="px-6 py-4 font-medium">Required / Multi</th>
                  <th className="px-6 py-4 font-medium">Max Size</th>
                  <th className="px-6 py-4 font-medium text-right">Actions</th>
                </tr>
              </thead>

              <tbody>
                {isLoading ? (
                  <tr>
                    <td colSpan={7} className="px-6 py-12 text-center">
                      <Loader2 className="mx-auto h-6 w-6 animate-spin text-[#10B981]" />
                      <p className="mt-2 text-sm text-slate-500">
                        Loading file upload settings…
                      </p>
                    </td>
                  </tr>
                ) : isError ? (
                  <tr>
                    <td colSpan={7} className="px-6 py-12 text-center">
                      <AlertCircle className="mx-auto h-6 w-6 text-red-500" />
                      <p className="mt-2 text-sm text-red-600">
                        Failed to load settings.{" "}
                        {error instanceof Error ? error.message : "Unknown error."}
                      </p>
                    </td>
                  </tr>
                ) : filtered.length === 0 ? (
                  <tr>
                    <td
                      colSpan={7}
                      className="px-6 py-12 text-center text-sm text-slate-500"
                    >
                      {fileUploadSettings.length === 0
                        ? "No file upload settings yet. Click \"New Setting\" to add one."
                        : "No file upload settings match your search."}
                    </td>
                  </tr>
                ) : (
                  filtered.map((setting) => {
                    const required = setting.fields.filter(
                      (f: any) => f.isRequired,
                    ).length;
                    const multi = setting.fields.filter(
                      (f: any) => f.isMultiple,
                    ).length;
                    const maxSize = Math.max(
                      0,
                      ...setting.fields.map((f) => f.maxSizeMb),
                    );

                    return (
                      <tr
                        key={setting.id}
                        className="border-t border-slate-100 transition hover:bg-[#10B981]/5"
                      >
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#10B981] text-white">
                              <FileUp className="h-5 w-5" />
                            </div>
                            <div>
                              <p className="font-medium text-slate-900">
                                {setting.label}
                              </p>
                              <p className="text-xs text-slate-500">
                                {setting.description ?? "No description"}
                              </p>
                            </div>
                          </div>
                        </td>

                        <td className="px-6 py-4">
                          <span className="rounded-md bg-slate-100 px-2 py-1 font-mono text-xs text-slate-700">
                            {setting.code}
                          </span>
                        </td>

                        <td className="px-6 py-4">
                          <span className="inline-flex rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-medium capitalize text-slate-600">
                            {setting.entity ?? "—"}
                          </span>
                        </td>

                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2 text-sm text-slate-700">
                            <Paperclip className="h-4 w-4 text-[#10B981]" />
                            <span className="font-medium">
                              {setting.fields.length}
                            </span>
                          </div>
                        </td>

                        <td className="px-6 py-4 text-sm text-slate-700">
                          <div className="flex flex-wrap items-center gap-1">
                            <Chip>{required} required</Chip>
                            <Chip muted>{multi} multi</Chip>
                          </div>
                        </td>

                        <td className="px-6 py-4 text-sm text-slate-700">
                          <div className="flex items-center gap-1.5">
                            <HardDrive className="h-4 w-4 text-slate-400" />
                            {maxSize ? `${maxSize} MB` : "—"}
                          </div>
                        </td>

                        <td className="px-6 py-4">
                          <div className="flex justify-end gap-2">
                            <ManageFileUploadFieldsDialog setting={setting}>
                              <button
                                type="button"
                                className="inline-flex items-center gap-1 rounded-xl border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 transition hover:border-[#10B981]/30 hover:bg-[#10B981]/10 hover:text-[#10B981]"
                              >
                                <Paperclip className="h-3.5 w-3.5" />
                                Fields
                              </button>
                            </ManageFileUploadFieldsDialog>

                            <EditFileUploadSettingDialog
                              mode="edit"
                              setting={setting}
                            >
                              <button
                                type="button"
                                className="rounded-xl border border-slate-200 p-2 text-slate-600 transition hover:border-[#10B981]/30 hover:bg-[#10B981]/10 hover:text-[#10B981]"
                              >
                                <Pencil className="h-4 w-4" />
                              </button>
                            </EditFileUploadSettingDialog>

                            <DeleteFileUploadSettingDialog
                              settingLabel={setting.label}
                              settingCode={setting.code}
                              onConfirm={() =>
                                deleteMutation.mutate(setting.id)
                              }
                            >
                              <button
                                type="button"
                                disabled={deleteMutation.isPending}
                                className="rounded-xl border border-red-200 p-2 text-red-600 transition hover:bg-red-50 disabled:cursor-not-allowed disabled:opacity-50"
                              >
                                <Trash2 className="h-4 w-4" />
                              </button>
                            </DeleteFileUploadSettingDialog>
                          </div>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Behavior reference card */}
        <div className="rounded-3xl bg-white p-6 shadow-sm">
          <h2 className="text-lg font-semibold text-slate-900">
            Required × Multiple behavior
          </h2>
          <p className="mt-1 text-sm text-slate-500">
            Min and max file counts are derived from these two toggles. The
            "Max Files" you set on a field is only used when{" "}
            <span className="font-medium">Multiple</span> is on.
          </p>
          <div className="mt-4 overflow-x-auto">
            <table className="w-full whitespace-nowrap text-left text-sm">
              <thead className="text-xs text-slate-500">
                <tr>
                  <th className="py-2 font-medium">Required</th>
                  <th className="py-2 font-medium">Multiple</th>
                  <th className="py-2 font-medium">min_files</th>
                  <th className="py-2 font-medium">max_files</th>
                </tr>
              </thead>
              <tbody>
                <BehaviorRow
                  required={false}
                  multiple={false}
                  min="0"
                  max="1"
                />
                <BehaviorRow
                  required={true}
                  multiple={false}
                  min="1"
                  max="1"
                />
                <BehaviorRow
                  required={false}
                  multiple={true}
                  min="0"
                  max="field.maxFiles"
                />
                <BehaviorRow
                  required={true}
                  multiple={true}
                  min="1"
                  max="field.maxFiles"
                />
              </tbody>
            </table>
          </div>
          <p className="mt-3 text-xs text-slate-500">
            Helpers <span className="font-mono">getMinFiles</span> and{" "}
            <span className="font-mono">getEffectiveMaxFiles</span> live in{" "}
            <span className="font-mono">@/types/fileUploadSettings</span> — use
            them when wiring real uploaders. Example: a field with{" "}
            <span className="font-mono">isRequired=false</span>,{" "}
            <span className="font-mono">isMultiple=true</span>,{" "}
            <span className="font-mono">maxFiles=5</span> gives{" "}
            <span className="font-mono">{getMinFiles({
              id: "demo",
              fileKey: "demo",
              fileLabel: "demo",
              isRequired: false,
              isMultiple: true,
              maxFiles: 5,
              allowedExtensions: [],
              maxSizeMb: 1,
            })}</span>
            …5.
          </p>
        </div>
      </div>
    </div>
  );
}

function BehaviorRow({
  required,
  multiple,
  min,
  max,
}: {
  required: boolean;
  multiple: boolean;
  min: string;
  max: string;
}) {
  return (
    <tr className="border-t border-slate-100">
      <td className="py-2.5">
        <Chip muted={!required}>{required ? "Required" : "Optional"}</Chip>
      </td>
      <td className="py-2.5">
        <Chip muted={!multiple}>{multiple ? "Multiple" : "Single"}</Chip>
      </td>
      <td className="py-2.5 font-mono text-slate-700">{min}</td>
      <td className="py-2.5 font-mono text-slate-700">{max}</td>
    </tr>
  );
}

function Chip({
  children,
  muted = false,
}: {
  children: React.ReactNode;
  muted?: boolean;
}) {
  return (
    <span
      className={
        muted
          ? "rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600"
          : "rounded-full bg-[#10B981]/10 px-2 py-0.5 text-xs font-medium text-[#10B981]"
      }
    >
      {children}
    </span>
  );
}

function StatCard({
  title,
  value,
  icon,
}: {
  title: string;
  value: string;
  icon: React.ReactNode;
}) {
  return (
    <div className="rounded-3xl bg-white p-6 shadow-sm transition hover:shadow-md hover:ring-1 hover:ring-[#10B981]/20">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm text-slate-500">{title}</p>
          <h3 className="mt-2 text-3xl font-bold text-slate-900">{value}</h3>
        </div>
        <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[#10B981] text-white">
          {icon}
        </div>
      </div>
    </div>
  );
}
