"use client";

import { useEffect, useMemo, useState } from "react";
import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { useSession } from "next-auth/react";
import DepartmentKpiTracker from "@/components/kpis/DepartmentKpiTracker";
import type { OperationsDashboardResponse } from "@/lib/operations";

type AssetPayload = {
  name: string;
  category: string;
  criticality: number;
};

type WorkOrderPayload = {
  assetId: string;
  title: string;
  dueBy: string;
  estimatedCost: number;
  expectedDowntimeHours: number;
};

type ForecastPayload = {
  lastWeekSales: number;
  multiplier: number;
};

type PlanPayload = {
  lineName: string;
  plannedUnits: number;
  capacityUnits: number;
};

type AssetOption = {
  id: string;
  name: string;
  assetCode: string;
};

export default function OperationsDepartmentPage() {
  const { data: session } = useSession();
  const [dashboard, setDashboard] = useState<OperationsDashboardResponse | null>(null);
  const [assets, setAssets] = useState<AssetOption[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isPublishing, setIsPublishing] = useState(false);

  const [assetDraft, setAssetDraft] = useState<AssetPayload>({ name: "", category: "", criticality: 3 });
  const [workOrderDraft, setWorkOrderDraft] = useState<WorkOrderPayload>({
    assetId: "",
    title: "",
    dueBy: "",
    estimatedCost: 0,
    expectedDowntimeHours: 0,
  });
  const [forecastDraft, setForecastDraft] = useState<ForecastPayload>({ lastWeekSales: 0, multiplier: 1.2 });
  const [planDraft, setPlanDraft] = useState<PlanPayload>({ lineName: "Línea principal", plannedUnits: 0, capacityUnits: 0 });

  const canManage = session?.user?.role === "owner" || (session?.user?.role === "leader" && session?.user?.department === "operaciones");
  const isOwner = session?.user?.role === "owner";

  const load = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const [dashboardResponse, assetsResponse] = await Promise.all([
        fetch("/api/operations/dashboard", { method: "GET", cache: "no-store" }),
        fetch("/api/operations/assets", { method: "GET", cache: "no-store" }),
      ]);

      const dashboardPayload = (await dashboardResponse.json()) as { error?: string } & OperationsDashboardResponse;
      if (!dashboardResponse.ok) {
        throw new Error(dashboardPayload.error ?? "No se pudo cargar Operaciones.");
      }

      const assetsPayload = (await assetsResponse.json()) as { error?: string; assets?: Array<{ id: string; name: string; assetCode: string }> };
      if (!assetsResponse.ok) {
        throw new Error(assetsPayload.error ?? "No se pudieron cargar activos.");
      }

      setDashboard(dashboardPayload);
      const nextAssets = (assetsPayload.assets ?? []).map((asset) => ({ id: asset.id, name: asset.name, assetCode: asset.assetCode }));
      setAssets(nextAssets);
      setWorkOrderDraft((prev) => ({ ...prev, assetId: prev.assetId || nextAssets[0]?.id || "" }));
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : "No se pudo cargar Operaciones.");
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    void load();
  }, []);

  const submitAsset = async () => {
    if (!assetDraft.name.trim() || !assetDraft.category.trim()) {
      return;
    }

    setError(null);
    try {
      const response = await fetch("/api/operations/assets", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(assetDraft),
      });

      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo crear activo.");
      }

      setAssetDraft({ name: "", category: "", criticality: 3 });
      await load();
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : "No se pudo crear activo.");
    }
  };

  const submitWorkOrder = async () => {
    if (!workOrderDraft.assetId || !workOrderDraft.title.trim()) {
      return;
    }

    setError(null);
    try {
      const response = await fetch("/api/operations/work-orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(workOrderDraft),
      });

      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo crear work order.");
      }

      setWorkOrderDraft((prev) => ({
        ...prev,
        title: "",
        dueBy: "",
        estimatedCost: 0,
        expectedDowntimeHours: 0,
      }));
      await load();
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : "No se pudo crear work order.");
    }
  };

  const submitForecast = async () => {
    setError(null);
    try {
      const response = await fetch("/api/operations/forecast", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(forecastDraft),
      });

      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo guardar forecast.");
      }

      await load();
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : "No se pudo guardar forecast.");
    }
  };

  const submitPlan = async () => {
    if (!planDraft.lineName.trim()) {
      return;
    }

    setError(null);
    try {
      const response = await fetch("/api/operations/production-plans", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(planDraft),
      });

      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo crear plan de producción.");
      }

      await load();
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : "No se pudo crear plan de producción.");
    }
  };

  const publishKpis = async () => {
    setError(null);
    setIsPublishing(true);
    try {
      const response = await fetch("/api/operations/kpi/publish", { method: "POST" });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo publicar KPI de operaciones.");
      }
      await load();
    } catch (publishError) {
      setError(publishError instanceof Error ? publishError.message : "No se pudo publicar KPI de operaciones.");
    } finally {
      setIsPublishing(false);
    }
  };

  const resolveApproval = async (approvalId: string, action: "approve" | "reject") => {
    setError(null);
    try {
      const response = await fetch(`/api/operations/approvals/${approvalId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action }),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo procesar la aprobación.");
      }
      await load();
    } catch (approvalError) {
      setError(approvalError instanceof Error ? approvalError.message : "No se pudo procesar la aprobación.");
    }
  };

  const workOrderChart = useMemo(() => dashboard?.workOrdersByState ?? [], [dashboard]);

  return (
    <div className="space-y-5">
      <header className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <h1 className="text-display">Operaciones · Mantenimiento y Fábrica</h1>
            <p className="text-body-lg text-benell-text-soft">Activos, PM, aprobaciones y planeación de producción basada en forecast.</p>
          </div>
          <button
            type="button"
            disabled={!canManage || isPublishing}
            onClick={() => void publishKpis()}
            className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-50"
          >
            {isPublishing ? "Publicando..." : "Publicar KPI owner"}
          </button>
        </div>
      </header>

      {error ? <p className="text-label text-benell-red">{error}</p> : null}
      {isLoading ? <p className="text-label text-benell-text-soft">Cargando Operaciones...</p> : null}

      <DepartmentKpiTracker
        department="operaciones"
        title="KPIs del área: Operaciones"
        description="Centraliza definición, evidencia, score y actualización de KPIs para Compras, Mantenimiento y CEDIS."
      />

      <section className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-5">
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <p className="text-label text-benell-text-soft">Activos</p>
          <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.summary.totalAssets ?? 0}</p>
          <p className="text-caption text-benell-text-soft">
            Críticos: {dashboard?.summary.criticalAssets ?? 0} · Down: {dashboard?.summary.downAssets ?? 0}
          </p>
        </article>
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <p className="text-label text-benell-text-soft">Work orders abiertas</p>
          <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.summary.openWorkOrders ?? 0}</p>
          <p className="text-caption text-benell-text-soft">Overdue: {dashboard?.summary.overdueWorkOrders ?? 0}</p>
        </article>
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <p className="text-label text-benell-text-soft">Aprobaciones pendientes</p>
          <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.summary.pendingApprovals ?? 0}</p>
        </article>
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <p className="text-label text-benell-text-soft">Forecast (semana)</p>
          <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.summary.forecastUnits ?? 0}</p>
        </article>
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <p className="text-label text-benell-text-soft">Plan vs forecast</p>
          <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.summary.actualVarianceUnits ?? 0}</p>
          <p className="text-caption text-benell-text-soft">Plan: {dashboard?.summary.plannedUnits ?? 0}</p>
        </article>
      </section>

      <section className="grid grid-cols-1 gap-4 xl:grid-cols-2">
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">Work orders por estado</h2>
          <div className="mt-3 h-64">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={workOrderChart}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="state" />
                <YAxis allowDecimals={false} />
                <Tooltip />
                <Bar dataKey="count" fill="#8a6a3d" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </article>

        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">Aprobación owner inbox</h2>
          <ul className="mt-3 space-y-2">
            {(dashboard?.approvalInbox ?? []).map((approval) => (
              <li key={approval.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                <p className="text-sm font-semibold text-benell-text">{approval.requestType}</p>
                <p className="text-caption text-benell-text-soft">
                  WO: {approval.workOrderId ?? "-"} · Plan: {approval.productionPlanId ?? "-"}
                </p>
                <p className="text-caption text-benell-text-soft">{approval.state} · {new Date(approval.createdAt).toLocaleString("es-MX")}</p>
                {approval.reason ? <p className="text-caption text-benell-text-soft">{approval.reason}</p> : null}
                {isOwner && (approval.state === "pending_owner" || approval.state === "submitted") ? (
                  <div className="mt-2 flex gap-2">
                    <button
                      type="button"
                      onClick={() => void resolveApproval(approval.id, "approve")}
                      className="rounded-pill bg-benell-green px-3 py-1.5 text-label font-semibold text-white"
                    >
                      Aprobar
                    </button>
                    <button
                      type="button"
                      onClick={() => void resolveApproval(approval.id, "reject")}
                      className="rounded-pill bg-benell-red px-3 py-1.5 text-label font-semibold text-white"
                    >
                      Rechazar
                    </button>
                  </div>
                ) : null}
              </li>
            ))}
          </ul>
        </article>

        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">PM próximo y vencido</h2>
          <ul className="mt-3 space-y-2">
            {(dashboard?.upcomingMaintenance ?? []).map((item) => (
              <li key={item.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                <p className="text-sm font-semibold text-benell-text">{item.assetName} · {item.title}</p>
                <p className="text-caption text-benell-text-soft">
                  Due: {new Date(item.dueBy).toLocaleDateString("es-MX")} · Estado: {item.state}
                </p>
              </li>
            ))}
          </ul>
        </article>
      </section>

      <section className="grid grid-cols-1 gap-4 xl:grid-cols-2">
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">Nuevo activo</h2>
          <div className="mt-3 grid grid-cols-1 gap-2">
            <input
              value={assetDraft.name}
              onChange={(event) => setAssetDraft((prev) => ({ ...prev, name: event.target.value }))}
              placeholder="Nombre del activo"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <input
              value={assetDraft.category}
              onChange={(event) => setAssetDraft((prev) => ({ ...prev, category: event.target.value }))}
              placeholder="Categoría"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <input
              type="number"
              min={1}
              max={5}
              value={assetDraft.criticality}
              onChange={(event) => setAssetDraft((prev) => ({ ...prev, criticality: Number(event.target.value) || 3 }))}
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <button
              type="button"
              onClick={() => void submitAsset()}
              disabled={!canManage}
              className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-50"
            >
              Crear activo
            </button>
          </div>
        </article>

        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">Nuevo work order</h2>
          <div className="mt-3 grid grid-cols-1 gap-2">
            <select
              value={workOrderDraft.assetId}
              onChange={(event) => setWorkOrderDraft((prev) => ({ ...prev, assetId: event.target.value }))}
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            >
              <option value="">Selecciona activo</option>
              {assets.map((asset) => (
                <option key={asset.id} value={asset.id}>
                  {asset.name} ({asset.assetCode})
                </option>
              ))}
            </select>
            <input
              value={workOrderDraft.title}
              onChange={(event) => setWorkOrderDraft((prev) => ({ ...prev, title: event.target.value }))}
              placeholder="Título"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <input
              type="date"
              value={workOrderDraft.dueBy}
              onChange={(event) => setWorkOrderDraft((prev) => ({ ...prev, dueBy: event.target.value }))}
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <input
              type="number"
              value={workOrderDraft.estimatedCost}
              onChange={(event) => setWorkOrderDraft((prev) => ({ ...prev, estimatedCost: Number(event.target.value) || 0 }))}
              placeholder="Costo estimado"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <input
              type="number"
              value={workOrderDraft.expectedDowntimeHours}
              onChange={(event) => setWorkOrderDraft((prev) => ({ ...prev, expectedDowntimeHours: Number(event.target.value) || 0 }))}
              placeholder="Downtime esperado (h)"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <button
              type="button"
              onClick={() => void submitWorkOrder()}
              disabled={!canManage}
              className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-50"
            >
              Crear work order
            </button>
          </div>
        </article>
      </section>

      <section className="grid grid-cols-1 gap-4 xl:grid-cols-2">
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">Forecast semanal (manual)</h2>
          <div className="mt-3 grid grid-cols-1 gap-2">
            <input
              type="number"
              value={forecastDraft.lastWeekSales}
              onChange={(event) => setForecastDraft((prev) => ({ ...prev, lastWeekSales: Number(event.target.value) || 0 }))}
              placeholder="Ventas semana pasada"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <input
              type="number"
              step="0.1"
              value={forecastDraft.multiplier}
              onChange={(event) => setForecastDraft((prev) => ({ ...prev, multiplier: Number(event.target.value) || 1.2 }))}
              placeholder="Multiplicador"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <button
              type="button"
              onClick={() => void submitForecast()}
              disabled={!canManage}
              className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-50"
            >
              Guardar forecast
            </button>
          </div>
        </article>

        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">Plan de producción</h2>
          <div className="mt-3 grid grid-cols-1 gap-2">
            <input
              value={planDraft.lineName}
              onChange={(event) => setPlanDraft((prev) => ({ ...prev, lineName: event.target.value }))}
              placeholder="Línea / célula"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <input
              type="number"
              value={planDraft.plannedUnits}
              onChange={(event) => setPlanDraft((prev) => ({ ...prev, plannedUnits: Number(event.target.value) || 0 }))}
              placeholder="Unidades planeadas"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <input
              type="number"
              value={planDraft.capacityUnits}
              onChange={(event) => setPlanDraft((prev) => ({ ...prev, capacityUnits: Number(event.target.value) || 0 }))}
              placeholder="Capacidad"
              className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              disabled={!canManage}
            />
            <button
              type="button"
              onClick={() => void submitPlan()}
              disabled={!canManage}
              className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-50"
            >
              Crear plan
            </button>
          </div>
        </article>
      </section>
    </div>
  );
}
