import type {
  ProjectCustomerOptionDto,
  ProjectDocumentOptionDto,
  ProjectInput,
  ProjectOwnerOptionDto,
  ProjectShipmentOptionDto,
} from "@mrp/shared/dist/projects/types.js";
import { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";

import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
import { emptyProjectInput, projectPriorityOptions, projectStatusOptions } from "./config";

export function ProjectFormPage({ mode }: { mode: "create" | "edit" }) {
  const { token, user } = useAuth();
  const navigate = useNavigate();
  const { projectId } = useParams();
  const [form, setForm] = useState<ProjectInput>(() => ({ ...emptyProjectInput, ownerId: user?.id ?? null }));
  const [customerOptions, setCustomerOptions] = useState<ProjectCustomerOptionDto[]>([]);
  const [ownerOptions, setOwnerOptions] = useState<ProjectOwnerOptionDto[]>([]);
  const [quoteOptions, setQuoteOptions] = useState<ProjectDocumentOptionDto[]>([]);
  const [orderOptions, setOrderOptions] = useState<ProjectDocumentOptionDto[]>([]);
  const [shipmentOptions, setShipmentOptions] = useState<ProjectShipmentOptionDto[]>([]);
  const [status, setStatus] = useState(mode === "create" ? "Create a new project." : "Loading project...");
  const [isSaving, setIsSaving] = useState(false);

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

    api.getProjectCustomerOptions(token).then(setCustomerOptions).catch(() => setCustomerOptions([]));
    api.getProjectOwnerOptions(token).then(setOwnerOptions).catch(() => setOwnerOptions([]));
  }, [token]);

  useEffect(() => {
    if (!token || !form.customerId) {
      setQuoteOptions([]);
      setOrderOptions([]);
      setShipmentOptions([]);
      return;
    }

    api.getProjectQuoteOptions(token, form.customerId).then(setQuoteOptions).catch(() => setQuoteOptions([]));
    api.getProjectOrderOptions(token, form.customerId).then(setOrderOptions).catch(() => setOrderOptions([]));
    api.getProjectShipmentOptions(token, form.customerId).then(setShipmentOptions).catch(() => setShipmentOptions([]));
  }, [form.customerId, token]);

  useEffect(() => {
    if (!token || mode !== "edit" || !projectId) {
      return;
    }

    api.getProject(token, projectId)
      .then((project) => {
        setForm({
          name: project.name,
          status: project.status,
          priority: project.priority,
          customerId: project.customerId,
          salesQuoteId: project.salesQuoteId,
          salesOrderId: project.salesOrderId,
          shipmentId: project.shipmentId,
          ownerId: project.ownerId,
          dueDate: project.dueDate,
          notes: project.notes,
        });
        setStatus("Project loaded.");
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load project.";
        setStatus(message);
      });
  }, [mode, projectId, token]);

  function updateField<Key extends keyof ProjectInput>(key: Key, value: ProjectInput[Key]) {
    setForm((current: ProjectInput) => ({
      ...current,
      [key]: value,
      ...(key === "customerId"
        ? {
            salesQuoteId: null,
            salesOrderId: null,
            shipmentId: null,
          }
        : {}),
    }));
  }

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

    setIsSaving(true);
    setStatus("Saving project...");
    try {
      const saved = mode === "create" ? await api.createProject(token, form) : await api.updateProject(token, projectId ?? "", form);
      navigate(`/projects/${saved.id}`);
    } catch (error: unknown) {
      const message = error instanceof ApiError ? error.message : "Unable to save project.";
      setStatus(message);
      setIsSaving(false);
    }
  }

  return (
    <form className="space-y-6" onSubmit={handleSubmit}>
      <section className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Projects Editor</p>
            <h3 className="mt-2 text-xl font-bold text-text">{mode === "create" ? "New Project" : "Edit Project"}</h3>
            <p className="mt-2 max-w-2xl text-sm text-muted">Create a customer-linked program record that can anchor commercial documents, delivery work, and project files.</p>
          </div>
          <Link to={mode === "create" ? "/projects" : `/projects/${projectId}`} className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text">
            Cancel
          </Link>
        </div>
      </section>
      <section className="space-y-4 rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="grid gap-3 xl:grid-cols-2">
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Project name</span>
            <input value={form.name} onChange={(event) => updateField("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">Customer</span>
            <select value={form.customerId} onChange={(event) => updateField("customerId", 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">
              <option value="">Select customer</option>
              {customerOptions.map((customer) => <option key={customer.id} value={customer.id}>{customer.name}</option>)}
            </select>
          </label>
        </div>
        <div className="grid gap-3 xl:grid-cols-4">
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Status</span>
            <select value={form.status} onChange={(event) => updateField("status", event.target.value as ProjectInput["status"])} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              {projectStatusOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Priority</span>
            <select value={form.priority} onChange={(event) => updateField("priority", event.target.value as ProjectInput["priority"])} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              {projectPriorityOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Owner</span>
            <select value={form.ownerId ?? ""} onChange={(event) => updateField("ownerId", event.target.value || null)} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              <option value="">Unassigned</option>
              {ownerOptions.map((owner) => <option key={owner.id} value={owner.id}>{owner.fullName}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Due date</span>
            <input type="date" value={form.dueDate ? form.dueDate.slice(0, 10) : ""} onChange={(event) => updateField("dueDate", event.target.value ? new Date(event.target.value).toISOString() : null)} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand" />
          </label>
        </div>
        <div className="grid gap-3 xl:grid-cols-3">
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Quote</span>
            <select value={form.salesQuoteId ?? ""} onChange={(event) => updateField("salesQuoteId", event.target.value || null)} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              <option value="">No linked quote</option>
              {quoteOptions.map((quote) => <option key={quote.id} value={quote.id}>{quote.documentNumber}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Sales order</span>
            <select value={form.salesOrderId ?? ""} onChange={(event) => updateField("salesOrderId", event.target.value || null)} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              <option value="">No linked sales order</option>
              {orderOptions.map((order) => <option key={order.id} value={order.id}>{order.documentNumber}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Shipment</span>
            <select value={form.shipmentId ?? ""} onChange={(event) => updateField("shipmentId", event.target.value || null)} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              <option value="">No linked shipment</option>
              {shipmentOptions.map((shipment) => <option key={shipment.id} value={shipment.id}>{shipment.shipmentNumber}</option>)}
            </select>
          </label>
        </div>
        <label className="block">
          <span className="mb-2 block text-sm font-semibold text-text">Notes</span>
          <textarea value={form.notes} onChange={(event) => updateField("notes", event.target.value)} rows={5} className="w-full rounded-3xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand" />
        </label>
        <div className="flex flex-col gap-3 rounded-2xl border border-line/70 bg-page/70 px-2 py-2 sm:flex-row sm:items-center sm:justify-between">
          <span className="min-w-0 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..." : mode === "create" ? "Create project" : "Save changes"}
          </button>
        </div>
      </section>
    </form>
  );
}
