"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useBrandingContext } from "@/components/app/BrandingProvider";
import { BrandingStyles } from "@/components/app/BrandingStyles";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input, Select } from "@/components/ui/Field";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import {
  AdminUser,
  ApiError,
  Branding,
  BranchItem,
  apiGet,
  apiPatch,
  deleteBranchLogo,
  deleteOrgLogo,
  deleteOrgFavicon,
  fetchBranchLogoMeta,
  getStoredUser,
  uploadBranchLogo,
  uploadOrgLogo,
  uploadOrgFavicon,
} from "@/lib/api";
import { DEFAULT_BRANDING } from "@school/ui";
import { brandingLogoUrl } from "@/lib/branding";
import { isHoldingAdmin } from "@/lib/permissions";
import { getActiveBranchId, getActiveRole } from "@/lib/session-context";

type Scope = "org" | number;

function ColorField({
  label,
  value,
  defaultValue,
  onChange,
}: {
  label: string;
  value: string;
  defaultValue: string;
  onChange: (value: string) => void;
}) {
  const isDefault = value.toLowerCase() === defaultValue.toLowerCase();

  return (
    <Field label={label}>
      <div className="flex items-center gap-2">
        <Input
          type="color"
          className="min-w-0 flex-1"
          value={value}
          onChange={(e) => onChange(e.target.value)}
        />
        <Button
          type="button"
          variant="secondary"
          className="shrink-0 px-3 py-2 text-xs"
          disabled={isDefault}
          onClick={() => onChange(defaultValue)}
        >
          پیش‌فرض
        </Button>
      </div>
    </Field>
  );
}

function LogoPreview({ branding, compact = false }: { branding: Branding; compact?: boolean }) {
  const logoSrc = brandingLogoUrl(branding.logo_url);
  const initials = branding.name?.charAt(0) ?? "م";

  return (
    <div className={`flex items-center gap-3 ${compact ? "" : "rounded-xl border border-[var(--border)] bg-slate-50 p-3"}`}>
      {logoSrc ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src={logoSrc}
          alt=""
          className={`shrink-0 rounded-lg object-contain bg-white ${compact ? "h-8 w-8" : "h-12 w-12"}`}
        />
      ) : (
        <div
          className={`flex shrink-0 items-center justify-center rounded-lg bg-teal-100 font-bold text-teal-800 ${
            compact ? "h-8 w-8 text-sm" : "h-12 w-12 text-lg"
          }`}
        >
          {initials}
        </div>
      )}
      <div className="min-w-0">
        <p className={`truncate font-bold text-slate-900 ${compact ? "text-xs" : "text-sm"}`}>
          {branding.admin_title}
        </p>
        <p className={`truncate text-[var(--muted)] ${compact ? "text-[10px]" : "text-xs"}`}>{branding.name}</p>
      </div>
    </div>
  );
}

export function BrandingSettingsPanel() {
  const user = useMemo(() => getStoredUser<AdminUser>(), []);
  const isSuperAdmin = isHoldingAdmin();
  const isBranchManager = getActiveRole() === "branch_manager" || Boolean(user?.roles.includes("branch_manager"));
  const { setBranding, refreshBranding } = useBrandingContext();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const faviconInputRef = useRef<HTMLInputElement>(null);

  const [scope, setScope] = useState<Scope>("org");
  const [branches, setBranches] = useState<BranchItem[]>([]);
  const [draft, setDraft] = useState<Branding | null>(null);
  const [logoInherits, setLogoInherits] = useState(true);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [applyToAllSchools, setApplyToAllSchools] = useState(false);
  const [logoBusy, setLogoBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  const activeBranchId = getActiveBranchId();
  const scopeBranchId = scope === "org" ? null : scope;

  const loadBranding = useCallback(async (branchId: number | null) => {
    const suffix = branchId ? `?branch_id=${branchId}` : "";
    const data = await apiGet<Branding>(`/branding${suffix}`);
    setDraft(data);
    return data;
  }, []);

  const loadBranchMeta = useCallback(async (branchId: number) => {
    const meta = await fetchBranchLogoMeta(branchId);
    setLogoInherits(meta.inherits);
  }, []);

  useEffect(() => {
    if (!isSuperAdmin && !isBranchManager) {
      setLoading(false);
      return;
    }

    const init = async () => {
      setLoading(true);
      setError(null);
      try {
        if (isSuperAdmin) {
          const branchList = await apiGet<BranchItem[]>("/branches");
          setBranches(branchList);
          await loadBranding(null);
        } else if (activeBranchId) {
          setScope(activeBranchId);
          await loadBranding(activeBranchId);
          await loadBranchMeta(activeBranchId);
        }
      } catch (err) {
        setError(err instanceof ApiError ? err.message : "خطا");
      } finally {
        setLoading(false);
      }
    };

    void init();
  }, [activeBranchId, isBranchManager, isSuperAdmin, loadBranchMeta, loadBranding]);

  useEffect(() => {
    if (!isSuperAdmin || loading) return;

    const reload = async () => {
      setError(null);
      try {
        if (scope === "org") {
          await loadBranding(null);
          setLogoInherits(true);
        } else {
          await loadBranding(scope);
          await loadBranchMeta(scope);
        }
      } catch (err) {
        setError(err instanceof ApiError ? err.message : "خطا");
      }
    };

    void reload();
  }, [scope, isSuperAdmin, loading, loadBranding, loadBranchMeta]);

  const save = async () => {
    if (!draft || !isSuperAdmin || scope !== "org") return;
    setSaving(true);
    setError(null);
    setMessage(null);
    try {
      const updated = await apiPatch<Branding>("/branding", {
        primary_color: draft.primary_color,
        secondary_color: draft.secondary_color,
        portal_title: draft.portal_title,
        admin_title: draft.admin_title,
        apply_to_all_schools: applyToAllSchools,
      });
      setDraft(updated);
      setBranding(updated);
      await refreshBranding();
      setMessage(
        applyToAllSchools
          ? "برندینگ هلدینگ ذخیره شد و روی همه مدارس اعمال شد."
          : "برندینگ هلدینگ ذخیره شد.",
      );
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ذخیره");
    } finally {
      setSaving(false);
    }
  };

  const onLogoSelected = async (file: File | null) => {
    if (!file || !draft) return;
    setLogoBusy(true);
    setError(null);
    setMessage(null);
    try {
      let updated: Branding;
      if (scope === "org") {
        updated = await uploadOrgLogo(file, scopeBranchId);
      } else {
        updated = await uploadBranchLogo(scope, file);
        setLogoInherits(false);
      }
      setDraft(updated);
      if (scope === "org" || scope === activeBranchId) {
        setBranding(updated);
        await refreshBranding();
      }
      setMessage("لوگو با موفقیت آپلود شد.");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در آپلود لوگو");
    } finally {
      setLogoBusy(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  const onDeleteLogo = async () => {
    if (!draft) return;
    setLogoBusy(true);
    setError(null);
    setMessage(null);
    try {
      let updated: Branding;
      if (scope === "org") {
        updated = await deleteOrgLogo(scopeBranchId);
      } else {
        updated = await deleteBranchLogo(scope);
        setLogoInherits(true);
      }
      setDraft(updated);
      if (scope === "org" || scope === activeBranchId) {
        setBranding(updated);
        await refreshBranding();
      }
      setMessage(scope === "org" ? "لوگوی هلدینگ حذف شد." : "لوگوی شعبه حذف شد و از هلدینگ ارث‌بری می‌شود.");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در حذف لوگو");
    } finally {
      setLogoBusy(false);
    }
  };

  const onInheritToggle = async (checked: boolean) => {
    if (scope === "org" || !checked) {
      setLogoInherits(checked);
      return;
    }
    await onDeleteLogo();
  };

  const onFaviconSelected = async (file: File | null) => {
    if (!file || !draft) return;
    setLogoBusy(true);
    setError(null);
    setMessage(null);
    try {
      const updated = await uploadOrgFavicon(file);
      setDraft(updated);
      setBranding(updated);
      await refreshBranding();
      setMessage("فای‌آیکن با موفقیت آپلود شد.");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در آپلود فای‌آیکن");
    } finally {
      setLogoBusy(false);
      if (faviconInputRef.current) faviconInputRef.current.value = "";
    }
  };

  const onDeleteFavicon = async () => {
    setLogoBusy(true);
    setError(null);
    setMessage(null);
    try {
      const updated = await deleteOrgFavicon();
      setDraft(updated);
      setBranding(updated);
      await refreshBranding();
      setMessage("فای‌آیکن هلدینگ حذف شد.");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در حذف فای‌آیکن");
    } finally {
      setLogoBusy(false);
    }
  };

  if (!isSuperAdmin && !isBranchManager) {
    return null;
  }

  const canEditColors = isSuperAdmin && scope === "org";
  const canEditLogo = isSuperAdmin || (isBranchManager && scope !== "org");

  return (
    <section className="space-y-4">
      {draft ? <BrandingStyles branding={draft} /> : null}
      <div>
        <h2 className="text-base font-semibold">برند و ظاهر</h2>
        <p className="mt-1 text-sm text-[var(--muted)]">لوگو، رنگ‌ها و عناوین پورتال و پنل مدیریت.</p>
      </div>
      {error ? <Alert tone="error">{error}</Alert> : null}
      {message ? <Alert tone="success">{message}</Alert> : null}

      {loading || !draft ? (
        <PageContentSkeleton rows={4} />
      ) : (
        <>
          {isSuperAdmin ? (
            <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card">
              <Field label="سطح برندینگ">
                <Select
                  value={scope === "org" ? "org" : String(scope)}
                  onChange={(e) => {
                    const value = e.target.value;
                    setScope(value === "org" ? "org" : Number(value));
                  }}
                >
                  <option value="org">هلدینگ — لوگای پیش‌فرض</option>
                  {branches.map((branch) => (
                    <option key={branch.id} value={branch.id}>
                      شعبه {branch.name}
                    </option>
                  ))}
                </Select>
              </Field>
            </div>
          ) : null}

          <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-5">
            <h3 className="mb-4 text-sm font-bold">لوگو</h3>

            {scope !== "org" ? (
              <label className="mb-4 flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={logoInherits}
                  onChange={(e) => void onInheritToggle(e.target.checked)}
                  disabled={logoBusy}
                />
                ارث‌بری لوگو از هلدینگ
              </label>
            ) : null}

            <div className="mb-4 flex flex-wrap items-start gap-4">
              <LogoPreview branding={draft} />
              {canEditLogo && (!logoInherits || scope === "org") ? (
                <div className="flex flex-wrap gap-2">
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/jpeg,image/png,image/webp,image/svg+xml"
                    className="hidden"
                    onChange={(e) => void onLogoSelected(e.target.files?.[0] ?? null)}
                  />
                  <Button
                    variant="secondary"
                    loading={logoBusy}
                    onClick={() => fileInputRef.current?.click()}
                  >
                    آپلود لوگو
                  </Button>
                  {draft.logo_url ? (
                    <Button variant="danger" loading={logoBusy} onClick={() => void onDeleteLogo()}>
                      حذف لوگو
                    </Button>
                  ) : null}
                </div>
              ) : null}
            </div>
            <p className="text-xs text-[var(--muted)]">فرمت‌های مجاز: JPEG، PNG، WebP، SVG — حداکثر ۲ مگابایت</p>
          </div>

          {isSuperAdmin && scope === "org" ? (
            <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-5">
              <h3 className="mb-4 text-sm font-bold">فای‌آیکن</h3>
              <div className="mb-4 flex flex-wrap items-start gap-4">
                {brandingLogoUrl(draft.favicon_url) ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={brandingLogoUrl(draft.favicon_url)!}
                    alt=""
                    className="h-12 w-12 rounded-lg border border-[var(--border)] bg-white object-contain p-1"
                  />
                ) : (
                  <div className="flex h-12 w-12 items-center justify-center rounded-lg border border-dashed border-slate-300 text-[10px] text-[var(--muted)]">
                    بدون آیکن
                  </div>
                )}
                <div className="flex flex-wrap gap-2">
                  <input
                    ref={faviconInputRef}
                    type="file"
                    accept="image/x-icon,image/vnd.microsoft.icon,image/png,image/jpeg,image/webp,image/svg+xml,.ico"
                    className="hidden"
                    onChange={(e) => void onFaviconSelected(e.target.files?.[0] ?? null)}
                  />
                  <Button
                    variant="secondary"
                    loading={logoBusy}
                    onClick={() => faviconInputRef.current?.click()}
                  >
                    آپلود فای‌آیکن
                  </Button>
                  {draft.favicon_url ? (
                    <Button variant="danger" loading={logoBusy} onClick={() => void onDeleteFavicon()}>
                      حذف فای‌آیکن
                    </Button>
                  ) : null}
                </div>
              </div>
              <p className="text-xs text-[var(--muted)]">فرمت‌های مجاز: ICO، PNG، JPEG، WebP، SVG — حداکثر ۱ مگابایت</p>
            </div>
          ) : null}

          <div className="grid gap-4 lg:grid-cols-2">
            <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card">
              <p className="mb-3 text-xs font-semibold text-[var(--muted)]">پیش‌نمایش سایدبار</p>
              <div className="rounded-xl border border-slate-200 bg-white p-3">
                <LogoPreview branding={draft} compact />
              </div>
            </div>
            <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card">
              <p className="mb-3 text-xs font-semibold text-[var(--muted)]">پیش‌نمایش هدر</p>
              <div
                className="rounded-xl px-4 py-3 text-white"
                style={{ background: "var(--header-gradient)" }}
              >
                <div className="flex items-center gap-3">
                  {brandingLogoUrl(draft.logo_url) ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={brandingLogoUrl(draft.logo_url)!}
                      alt=""
                      className="h-9 w-9 rounded-lg bg-white/10 object-contain"
                    />
                  ) : (
                    <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/15 text-sm font-bold">
                      {draft.name?.charAt(0) ?? "م"}
                    </div>
                  )}
                  <div>
                    <p className="text-sm font-bold">{draft.admin_title}</p>
                    <p className="text-[11px] text-white/80">{draft.name}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {canEditColors ? (
            <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-5">
              <div className="mb-5 grid gap-3 sm:grid-cols-2">
                <div
                  className="rounded-2xl p-5 text-white"
                  style={{ background: "var(--header-gradient)" }}
                >
                  <p className="text-xs opacity-80">پیش‌نمایش Admin</p>
                  <p className="mt-1 text-lg font-bold">{draft.admin_title}</p>
                  <p className="text-xs opacity-80">{draft.name}</p>
                </div>
                <div
                  className="rounded-2xl p-5 text-white"
                  style={{ background: "var(--header-gradient)" }}
                >
                  <p className="text-xs opacity-80">پیش‌نمایش Portal</p>
                  <p className="mt-1 text-lg font-bold">{draft.portal_title}</p>
                  <p className="text-xs opacity-80">{draft.name}</p>
                </div>
              </div>

              <div className="grid gap-4 sm:grid-cols-2">
                <ColorField
                  label="رنگ اصلی"
                  value={draft.primary_color}
                  defaultValue={DEFAULT_BRANDING.primary_color}
                  onChange={(primary_color) => setDraft({ ...draft, primary_color })}
                />
                <ColorField
                  label="رنگ ثانویه"
                  value={draft.secondary_color}
                  defaultValue={DEFAULT_BRANDING.secondary_color}
                  onChange={(secondary_color) => setDraft({ ...draft, secondary_color })}
                />
                <Field label="عنوان پورتال">
                  <Input
                    value={draft.portal_title}
                    onChange={(e) => setDraft({ ...draft, portal_title: e.target.value })}
                  />
                </Field>
                <Field label="عنوان پنل">
                  <Input
                    value={draft.admin_title}
                    onChange={(e) => setDraft({ ...draft, admin_title: e.target.value })}
                  />
                </Field>
              </div>

              <div className="mt-5 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <label className="inline-flex max-w-md items-start gap-2 text-sm">
                  <input
                    type="checkbox"
                    className="mt-0.5 h-4 w-4 rounded border-slate-300 text-primary"
                    checked={applyToAllSchools}
                    onChange={(e) => setApplyToAllSchools(e.target.checked)}
                  />
                  <span>
                    ذخیره برای کلیه مدارس
                    <span className="mt-0.5 block text-xs font-normal text-[var(--muted)]">
                      برندینگ هلدینگ روی همه مدارس اعمال می‌شود و تنظیمات اختصاصی شعب پاک می‌شود.
                    </span>
                  </span>
                </label>
                <Button className="min-w-40" loading={saving} onClick={() => void save()}>
                  ذخیره برندینگ
                </Button>
              </div>
            </div>
          ) : null}
        </>
      )}
    </section>
  );
}
