"use client";

import { useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
  Badge,
  Button,
  Field,
  Input,
  Switch,
  Modal,
  PageHeader,
} from "@/components/ui";
import { EditIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";

interface Theme {
  id: number;
  key: string;
  name: string;
  colors: Record<string, string>;
  order?: number;
  is_active?: boolean;
}

// "#FF156395" (ARGB) or "#156395" → a CSS color the browser understands.
function cssColor(c?: string): string {
  if (!c) return "transparent";
  const hex = c.replace("#", "");
  if (hex.length === 8) return `#${hex.slice(2)}${hex.slice(0, 2)}`; // ARGB → RGBA
  return `#${hex}`;
}

// The RGB part for a native <input type="color"> (which can't represent alpha).
function toNativeRgb(argb?: string): string {
  const hex = (argb ?? "").replace("#", "");
  if (hex.length === 8) return `#${hex.slice(2)}`;
  if (hex.length === 6) return `#${hex}`;
  return "#000000";
}

// Editable color cell: a native picker for the RGB part (preserving any alpha)
// plus a free-text field for full ARGB control.
function ColorInput({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  const hex = (value ?? "").replace("#", "");
  const alpha = hex.length === 8 ? hex.slice(0, 2) : "";
  return (
    <div className="flex items-center gap-2">
      <input
        type="color"
        aria-label="انتخاب رنگ"
        value={toNativeRgb(value)}
        onChange={(e) =>
          onChange(`#${alpha}${e.target.value.replace("#", "")}`.toUpperCase())
        }
        className="h-9 w-9 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0.5"
      />
      <Input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        dir="ltr"
        className="font-mono"
        placeholder="#FFFFFFFF"
      />
    </div>
  );
}

export default function ThemesPage() {
  // include_inactive so the editor also lists themes that are turned off.
  const { data, loading, error, reload } = useList<Theme>("/themes", {
    include_inactive: 1,
  });
  const toast = useToast();

  const [editing, setEditing] = useState<Theme | null>(null);
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);

  const [name, setName] = useState("");
  const [order, setOrder] = useState("");
  const [isActive, setIsActive] = useState(true);
  const [colors, setColors] = useState<Record<string, string>>({});

  function openEdit(row: Theme) {
    setEditing(row);
    setName(row.name ?? "");
    setOrder(row.order != null ? String(row.order) : "");
    setIsActive(row.is_active ?? true);
    // Clone so edits don't mutate the loaded row before saving.
    setColors({ ...(row.colors ?? {}) });
    setOpen(true);
  }

  function setColor(key: string, value: string) {
    setColors((prev) => ({ ...prev, [key]: value }));
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    if (!editing) return;
    setSaving(true);
    try {
      await apiFetch(`/themes/${editing.id}`, {
        method: "PUT",
        body: {
          name,
          order: order === "" ? undefined : Number(order),
          is_active: isActive,
          colors,
        },
      });
      toast.success("تم ویرایش شد.");
      setOpen(false);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
    } finally {
      setSaving(false);
    }
  }

  const swatchKeys = [
    "themeUp",
    "themeDown",
    "lightColorGradient",
    "darkColorGradient",
  ];

  const columns: Column<Theme>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
    {
      key: "preview",
      header: "پیش‌نمایش",
      render: (r) => (
        <span className="inline-flex overflow-hidden rounded-full border border-border">
          {swatchKeys.map((k) => (
            <span
              key={k}
              className="h-5 w-5"
              style={{ backgroundColor: cssColor(r.colors?.[k]) }}
            />
          ))}
        </span>
      ),
      className: "w-32",
    },
    { key: "name", header: "نام" },
    {
      key: "key",
      header: "کلید",
      render: (r) => <span dir="ltr" className="font-mono">{r.key}</span>,
      className: "w-28",
    },
    {
      key: "order",
      header: "ترتیب",
      render: (r) => toFa(r.order ?? 0),
      className: "w-20",
    },
    {
      key: "is_active",
      header: "وضعیت",
      render: (r) =>
        r.is_active ? (
          <Badge tone="success">فعال</Badge>
        ) : (
          <Badge>غیرفعال</Badge>
        ),
      className: "w-24",
    },
  ];

  return (
    <div>
      <PageHeader
        title="تم‌ها"
        subtitle="ویرایش رنگ‌های تم‌های صحنه"
      />

      <DataTable
        columns={columns}
        rows={data}
        loading={loading}
        error={error}
        onRetry={reload}
        emptyMessage="هنوز تمی ثبت نشده است."
        actions={(row) => (
          <Button variant="ghost" onClick={() => openEdit(row)} aria-label="ویرایش">
            <EditIcon className="h-4 w-4" />
          </Button>
        )}
      />

      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={editing ? `ویرایش تم «${editing.name}»` : "ویرایش تم"}
        footer={
          <>
            <Button variant="secondary" onClick={() => setOpen(false)}>
              انصراف
            </Button>
            <Button form="theme-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="theme-form" onSubmit={save} className="flex flex-col gap-4">
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <Field label="نام" required>
              <Input
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
              />
            </Field>
            <Field label="ترتیب">
              <Input
                type="number"
                value={order}
                onChange={(e) => setOrder(e.target.value)}
                dir="ltr"
              />
            </Field>
          </div>

          <Field label="فعال">
            <Switch checked={isActive} onChange={setIsActive} />
          </Field>

          <div className="border-t border-border pt-4">
            <p className="mb-3 text-sm font-medium text-foreground">رنگ‌ها</p>
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              {Object.keys(colors).map((key) => (
                <Field key={key} label={key}>
                  <ColorInput
                    value={colors[key] ?? ""}
                    onChange={(v) => setColor(key, v)}
                  />
                </Field>
              ))}
            </div>
          </div>
        </form>
      </Modal>
    </div>
  );
}
