import { permissions, type ManufacturingStationInput, type ManufacturingStationDto } from "@mrp/shared";
import { useEffect, useState } from "react";

import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
import { WorkOrderListPage } from "./WorkOrderListPage";

const emptyStationInput: ManufacturingStationInput = {
  code: "",
  name: "",
  description: "",
  queueDays: 0,
  isActive: true,
};

export function ManufacturingPage() {
  const { token, user } = useAuth();
  const [stations, setStations] = useState<ManufacturingStationDto[]>([]);
  const [form, setForm] = useState<ManufacturingStationInput>(emptyStationInput);
  const [status, setStatus] = useState("Define manufacturing stations once so routings and work orders can schedule automatically.");
  const [isSaving, setIsSaving] = useState(false);
  const canManage = user?.permissions.includes(permissions.manufacturingWrite) ?? false;

  useEffect(() => {
    if (!token) {
      return;
    }

    api.getManufacturingStations(token).then(setStations).catch(() => setStations([]));
  }, [token]);

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!token) {
      return;
    }

    setIsSaving(true);
    setStatus("Saving station...");
    try {
      const station = await api.createManufacturingStation(token, form);
      setStations((current) => [...current, station].sort((left, right) => left.code.localeCompare(right.code)));
      setForm(emptyStationInput);
      setStatus("Station saved.");
    } catch (error: unknown) {
      const message = error instanceof ApiError ? error.message : "Unable to save station.";
      setStatus(message);
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <div className="space-y-4">
      <section className="grid gap-3 xl:grid-cols-[minmax(0,1.05fr)_400px]">
        <article className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Manufacturing Stations</p>
          <h3 className="mt-2 text-xl font-bold text-text">Scheduling anchors</h3>
          <p className="mt-2 text-sm text-muted">Stations define where operation time belongs. Buildable items reference them in their routing template, and work orders inherit those steps automatically into planning.</p>
          {stations.length === 0 ? (
            <div className="mt-5 rounded-[18px] border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">
              No stations defined yet.
            </div>
          ) : (
            <div className="mt-5 space-y-3">
              {stations.map((station) => (
                <article key={station.id} className="rounded-[18px] border border-line/70 bg-page/60 p-3">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="font-semibold text-text">{station.code} - {station.name}</div>
                      <div className="mt-1 text-xs text-muted">{station.description || "No description"}</div>
                    </div>
                    <div className="text-right text-xs text-muted">
                      <div>{station.queueDays} expected wait day(s)</div>
                      <div className="mt-1">{station.isActive ? "Active" : "Inactive"}</div>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          )}
        </article>
        {canManage ? (
          <form onSubmit={handleSubmit} className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">New Station</p>
            <div className="mt-4 grid gap-3">
              <label className="block">
                <span className="mb-2 block text-sm font-semibold text-text">Code</span>
                <input value={form.code} onChange={(event) => setForm((current) => ({ ...current, code: event.target.value }))} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand" />
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-semibold text-text">Name</span>
                <input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand" />
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-semibold text-text">Expected Wait (Days)</span>
                <input type="number" min={0} step={1} value={form.queueDays} onChange={(event) => setForm((current) => ({ ...current, queueDays: Number.parseInt(event.target.value, 10) || 0 }))} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand" />
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-semibold text-text">Description</span>
                <textarea value={form.description} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} rows={3} className="w-full rounded-[18px] border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand" />
              </label>
              <label className="flex items-center gap-3 rounded-2xl border border-line/70 bg-page px-2 py-2">
                <input type="checkbox" checked={form.isActive} onChange={(event) => setForm((current) => ({ ...current, isActive: event.target.checked }))} />
                <span className="text-sm font-semibold text-text">Active station</span>
              </label>
              <div className="flex flex-col gap-3 rounded-2xl border border-line/70 bg-page/70 px-2 py-2">
                <span className="text-sm text-muted">{status}</span>
                <button type="submit" disabled={isSaving} className="rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:opacity-60">
                  {isSaving ? "Saving..." : "Create station"}
                </button>
              </div>
            </div>
          </form>
        ) : null}
      </section>
      <WorkOrderListPage />
    </div>
  );
}

