import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { usePermissions } from "@/hooks/use-permissions";
import { supabase } from "@/integrations/supabase/client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { ArrowLeft, Save, RotateCcw, Loader2, ShieldAlert } from "lucide-react";
import {
  SALE_STATUSES,
  STATUS_COLORS,
  statusLabel,
  type SaleStatus,
} from "@/components/sales/sale-status";
import { DEFAULT_TRANSITIONS } from "@/hooks/use-sale-status-rules";

export const Route = createFileRoute("/_authenticated/sale-status-rules")({
  head: () => ({ meta: [{ title: "Sale Status Rules — Niyamah ERP" }] }),
  component: SaleStatusRulesPage,
});

type RulesMap = Record<string, SaleStatus[]>;

function SaleStatusRulesPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const { user } = useAuth();
  const { isAdmin } = usePermissions();
  const qc = useQueryClient();

  const { data: rows = [], isLoading } = useQuery({
    queryKey: ["sale-status-transitions-admin"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("sale_status_transitions" as any)
        .select("from_status, allowed_to, updated_at")
        .order("from_status");
      if (error) throw error;
      return (data as any[]) || [];
    },
  });

  const [draft, setDraft] = useState<RulesMap>({});
  const [dirty, setDirty] = useState(false);

  useEffect(() => {
    if (!isLoading) {
      const map: RulesMap = {};
      for (const s of SALE_STATUSES) map[s] = [];
      for (const r of rows as any[]) {
        map[r.from_status] = (r.allowed_to || []) as SaleStatus[];
      }
      setDraft(map);
      setDirty(false);
    }
  }, [rows, isLoading]);

  const toggle = (from: SaleStatus, to: SaleStatus) => {
    setDraft((prev) => {
      const cur = new Set(prev[from] || []);
      if (cur.has(to)) cur.delete(to);
      else cur.add(to);
      return { ...prev, [from]: Array.from(cur) };
    });
    setDirty(true);
  };

  const resetRow = (from: SaleStatus) => {
    setDraft((prev) => ({ ...prev, [from]: DEFAULT_TRANSITIONS[from] || [] }));
    setDirty(true);
  };

  const resetAll = () => {
    const m: RulesMap = {};
    for (const s of SALE_STATUSES) m[s] = DEFAULT_TRANSITIONS[s] || [];
    setDraft(m);
    setDirty(true);
  };

  const saveMut = useMutation({
    mutationFn: async () => {
      const payload = SALE_STATUSES.map((s) => ({
        from_status: s,
        allowed_to: draft[s] || [],
        updated_at: new Date().toISOString(),
        updated_by: user?.id ?? null,
      }));
      const { error } = await supabase
        .from("sale_status_transitions" as any)
        .upsert(payload as any, { onConflict: "from_status" });
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "নিয়মাবলী সংরক্ষণ হয়েছে" : "Rules saved");
      qc.invalidateQueries({ queryKey: ["sale-status-transitions"] });
      qc.invalidateQueries({ queryKey: ["sale-status-transitions-admin"] });
      setDirty(false);
    },
    onError: (e: any) => toast.error(e.message),
  });

  if (!isAdmin) {
    return (
      <PageLayout>
        <div className="rounded-xl border border-border bg-card p-8 text-center">
          <ShieldAlert className="h-10 w-10 mx-auto text-destructive mb-3" />
          <h1 className="text-lg font-semibold">{isBn ? "অনুমতি নেই" : "Access denied"}</h1>
          <p className="text-sm text-muted-foreground mt-1">
            {isBn ? "এই পেজ শুধু সুপার অ্যাডমিন দেখতে পারবেন।" : "Only super admins can view this page."}
          </p>
        </div>
      </PageLayout>
    );
  }

  return (
    <PageLayout>
      <div className="mb-6 flex items-center justify-between flex-wrap gap-3">
        <div>
          <Link to="/settings" className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground mb-2">
            <ArrowLeft className="h-4 w-4" />
            {isBn ? "সেটিংস" : "Settings"}
          </Link>
          <h1 className="text-xl font-bold text-foreground">
            {isBn ? "সেল স্ট্যাটাস ট্রানজিশন নিয়মাবলী" : "Sale Status Transition Rules"}
          </h1>
          <p className="text-sm text-muted-foreground">
            {isBn
              ? "প্রতিটি স্ট্যাটাস থেকে কোন কোন পরবর্তী স্ট্যাটাসে যাওয়া যাবে তা নির্ধারণ করুন।"
              : "Configure which next statuses are allowed from each current status."}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={resetAll}
            className="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-muted"
          >
            <RotateCcw className="h-4 w-4" />
            {isBn ? "ডিফল্টে রিসেট" : "Reset to defaults"}
          </button>
          <button
            onClick={() => saveMut.mutate()}
            disabled={!dirty || saveMut.isPending}
            className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:opacity-90 disabled:opacity-50"
          >
            {saveMut.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            {isBn ? "সংরক্ষণ" : "Save"}
          </button>
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border bg-muted/30 text-left text-xs text-muted-foreground">
              <th className="px-4 py-3 font-medium w-48">
                {isBn ? "বর্তমান স্ট্যাটাস" : "From Status"}
              </th>
              <th className="px-4 py-3 font-medium">
                {isBn ? "অনুমোদিত পরবর্তী স্ট্যাটাস" : "Allowed Next Statuses"}
              </th>
              <th className="px-4 py-3 font-medium text-right w-32">
                {isBn ? "অ্যাকশন" : "Actions"}
              </th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr>
                <td colSpan={3} className="px-4 py-10 text-center text-muted-foreground">
                  {isBn ? "লোড হচ্ছে..." : "Loading..."}
                </td>
              </tr>
            ) : (
              SALE_STATUSES.map((from) => {
                const selected = new Set(draft[from] || []);
                return (
                  <tr key={from} className="border-b border-border last:border-0 align-top">
                    <td className="px-4 py-4">
                      <span
                        className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold ${STATUS_COLORS[from]}`}
                      >
                        {statusLabel(from, isBn)}
                      </span>
                      <div className="text-[11px] text-muted-foreground mt-1 font-mono">{from}</div>
                    </td>
                    <td className="px-4 py-4">
                      <div className="flex flex-wrap gap-2">
                        {SALE_STATUSES.filter((t) => t !== from).map((to) => {
                          const active = selected.has(to);
                          return (
                            <button
                              key={to}
                              onClick={() => toggle(from, to)}
                              className={`rounded-full border px-2.5 py-1 text-xs font-medium transition ${
                                active
                                  ? `${STATUS_COLORS[to]} ring-2 ring-primary`
                                  : "border-border bg-card text-muted-foreground hover:bg-muted"
                              }`}
                            >
                              {statusLabel(to, isBn)}
                            </button>
                          );
                        })}
                      </div>
                      {selected.size === 0 && (
                        <div className="text-[11px] text-muted-foreground mt-2">
                          {isBn ? "টার্মিনাল — কোনো পরিবর্তন অনুমোদিত নয়" : "Terminal — no transitions allowed"}
                        </div>
                      )}
                    </td>
                    <td className="px-4 py-4 text-right">
                      <button
                        onClick={() => resetRow(from)}
                        className="inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-xs hover:bg-muted"
                        title={isBn ? "এই সারির ডিফল্ট" : "Default for this row"}
                      >
                        <RotateCcw className="h-3 w-3" />
                        {isBn ? "ডিফল্ট" : "Default"}
                      </button>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      {dirty && (
        <div className="mt-3 text-xs text-amber-600 dark:text-amber-400">
          {isBn ? "অসংরক্ষিত পরিবর্তন আছে — সংরক্ষণ করুন।" : "Unsaved changes — click Save."}
        </div>
      )}
    </PageLayout>
  );
}
