"use client";

import { ReactNode, useActionState, useEffect, useRef } from "react";
import { useFormStatus } from "react-dom";
import { Loader2, CheckCircle2, AlertCircle } from "lucide-react";
import {
  ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  PieChart, Pie, Cell, LineChart, Line, Legend,
} from "recharts";

type State = { ok?: boolean; error?: string; msg?: string };
type Action = (prev: State, fd: FormData) => Promise<State>;

export function SubmitBtn({ children, className = "", pendingText = "در حال ذخیره..." }: { children: ReactNode; className?: string; pendingText?: string }) {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending}
      className={`inline-flex items-center justify-center gap-2 rounded-xl bg-gradient-to-l from-emerald-700 to-emerald-900 px-5 py-2.5 text-sm font-extrabold text-white shadow-md shadow-emerald-900/25 transition hover:brightness-110 active:scale-[0.98] disabled:opacity-60 ${className}`}>
      {pending && <Loader2 size={16} className="animate-spin" />}
      {pending ? pendingText : children}
    </button>
  );
}

export function GhostBtn({ children, className = "" }: { children: ReactNode; className?: string }) {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending}
      className={`inline-flex items-center justify-center gap-1.5 rounded-lg border border-emerald-900/15 bg-white px-3 py-1.5 text-xs font-bold text-emerald-800 transition hover:bg-emerald-50 active:scale-[0.97] disabled:opacity-50 ${className}`}>
      {pending ? <Loader2 size={13} className="animate-spin" /> : null}
      {children}
    </button>
  );
}

export function ActionForm({ action, children, className = "", resetOnSuccess = false }:
  { action: Action; children: ReactNode; className?: string; resetOnSuccess?: boolean }) {
  const [state, formAction, pending] = useActionState(action, {} as State);
  const ref = useRef<HTMLFormElement>(null);
  useEffect(() => {
    if (state.ok && resetOnSuccess) ref.current?.reset();
  }, [state, resetOnSuccess]);
  return (
    <form ref={ref} action={formAction} className={className}>
      {children}
      <div aria-live="polite">
        {state.error && (
          <div className="mt-3 flex items-center gap-2 rounded-xl border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs font-bold text-red-700">
            <AlertCircle size={15} /> {state.error}
          </div>
        )}
        {state.ok && state.msg && (
          <div className="mt-3 flex items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-3.5 py-2.5 text-xs font-bold text-emerald-700">
            <CheckCircle2 size={15} /> {state.msg}
          </div>
        )}
      </div>
      <input type="hidden" name="_p" value={String(pending)} readOnly />
    </form>
  );
}

export function ConfirmSubmit({ children, message = "آیا مطمئن هستید؟", className = "" }:
  { children: ReactNode; message?: string; className?: string }) {
  return (
    <button type="submit" className={className} onClick={(e) => { if (!window.confirm(message)) e.preventDefault(); }}>
      {children}
    </button>
  );
}

export function PrintButton({ label = "چاپ" }: { label?: string }) {
  return (
    <button onClick={() => window.print()}
      className="inline-flex items-center gap-1.5 rounded-xl border border-emerald-900/15 bg-white px-4 py-2 text-xs font-bold text-emerald-800 hover:bg-emerald-50 print:hidden">
      {label}
    </button>
  );
}

/* ---------------- نمودارها ---------------- */
const FA = (n: number) => String(n).replace(/[0-9]/g, (d) => "۰۱۲۳۴۵۶۷۸۹"[+d]);
const tooltipStyle = { fontFamily: "inherit", fontSize: 12, borderRadius: 12, border: "1px solid #064e3b22" };

export function BarChartBox({ data, xKey, yKey, color = "#047857", height = 260 }: {
  data: Record<string, unknown>[]; xKey: string; yKey: string; color?: string; height?: number;
}) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={data} margin={{ top: 8, left: 0, right: 8, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="#064e3b18" vertical={false} />
        <XAxis dataKey={xKey} tick={{ fontSize: 11, fill: "#064e3b" }} axisLine={false} tickLine={false} />
        <YAxis tick={{ fontSize: 11, fill: "#064e3b" }} axisLine={false} tickLine={false} tickFormatter={FA} width={30} />
        <Tooltip contentStyle={tooltipStyle} formatter={(v) => FA(Number(v))} cursor={{ fill: "#04785710" }} />
        <Bar dataKey={yKey} fill={color} radius={[6, 6, 0, 0]} maxBarSize={42} />
      </BarChart>
    </ResponsiveContainer>
  );
}

export function LineChartBox({ data, xKey, yKey, color = "#d97706", height = 260 }: {
  data: Record<string, unknown>[]; xKey: string; yKey: string; color?: string; height?: number;
}) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <LineChart data={data} margin={{ top: 8, left: 0, right: 8, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="#064e3b18" vertical={false} />
        <XAxis dataKey={xKey} tick={{ fontSize: 11, fill: "#064e3b" }} axisLine={false} tickLine={false} />
        <YAxis tick={{ fontSize: 11, fill: "#064e3b" }} axisLine={false} tickLine={false} tickFormatter={FA} width={30} />
        <Tooltip contentStyle={tooltipStyle} formatter={(v) => FA(Number(v))} />
        <Line type="monotone" dataKey={yKey} stroke={color} strokeWidth={2.5} dot={{ r: 4, fill: color }} />
      </LineChart>
    </ResponsiveContainer>
  );
}

const PIE_COLORS = ["#047857", "#d97706", "#0369a1", "#be123c", "#7c3aed", "#0d9488", "#b45309"];
export function PieChartBox({ data, nameKey, valueKey, height = 260 }: {
  data: Record<string, unknown>[]; nameKey: string; valueKey: string; height?: number;
}) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <PieChart>
        <Pie data={data} dataKey={valueKey} nameKey={nameKey} innerRadius={52} outerRadius={88} paddingAngle={3} strokeWidth={2}>
          {data.map((_, i) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
        </Pie>
        <Tooltip contentStyle={tooltipStyle} formatter={(v) => FA(Number(v))} />
        <Legend formatter={(v) => <span style={{ fontSize: 12, color: "#064e3b" }}>{v}</span>} />
      </PieChart>
    </ResponsiveContainer>
  );
}
