"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { updatePo } from "./actions";
import type { Vendor, PurchaseOrder } from "@prisma/client";
import type { VesselOption, AccountGroup, CompanyOption } from "@/app/(portal)/po/new/new-po-form";
import { LineItemsEditor } from "@/components/po/po-line-items-editor";
import { SearchableSelect } from "@/components/ui/searchable-select";
import type { LineItemInput } from "@/lib/validations/po";
import { TC_DEFAULTS, TC_FIXED_LINE, TC_FIXED_LINE_2 } from "@/lib/validations/po";

const INPUT_CLS =
  "w-full rounded-lg border border-neutral-300 px-3 py-2.5 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20";

type SerializedLineItem = {
  id: string;
  poId: string;
  name: string;
  description: string | null;
  quantity: number;
  unit: string;
  size: string | null;
  unitPrice: number;
  totalPrice: number;
  gstRate: number;
  sortOrder: number;
  productId: string | null;
  accountId: string | null;
};

type PoWithItems = Omit<PurchaseOrder, "totalAmount"> & {
  totalAmount: number;
  lineItems: SerializedLineItem[];
};

interface Props {
  po: PoWithItems;
  vessels: VesselOption[];
  accounts: AccountGroup[];
  vendors: Vendor[];
  companies: CompanyOption[];
  managerNoteAuthor?: string | null;
}

export function EditPoForm({ po, vessels, accounts, vendors, companies, managerNoteAuthor }: Props) {
  const router = useRouter();
  const [lineItems, setLineItems] = useState<LineItemInput[]>(
    po.lineItems.map((li) => ({
      name: li.name,
      description: li.description ?? undefined,
      quantity: li.quantity,
      unit: li.unit,
      size: li.size ?? undefined,
      unitPrice: li.unitPrice,
      gstRate: li.gstRate,
      accountId: li.accountId ?? undefined,
    }))
  );
  const [submitting, setSubmitting] = useState<"save" | "submit" | "resubmit" | null>(null);
  const [error, setError] = useState("");
  const hasPerLineAccounts = po.lineItems.some((li) => li.accountId);
  const [multiAccount, setMultiAccount] = useState(hasPerLineAccounts);
  const [defaultAccountId, setDefaultAccountId] = useState(po.accountId ?? "");

  const canSubmit   = po.status === "DRAFT";
  const canResubmit = po.status === "EDITS_REQUESTED";

  async function handleSubmit(intent: "save" | "submit" | "resubmit") {
    setSubmitting(intent);
    setError("");
    const form = document.getElementById("edit-po-form") as HTMLFormElement;
    const data = new FormData(form);
    data.set("intent", intent);
    lineItems.forEach((item, i) => {
      data.set(`lineItems[${i}].name`, item.name);
      data.set(`lineItems[${i}].description`, item.description ?? "");
      data.set(`lineItems[${i}].quantity`, String(item.quantity));
      data.set(`lineItems[${i}].unit`, item.unit);
      data.set(`lineItems[${i}].size`, item.size ?? "");
      data.set(`lineItems[${i}].unitPrice`, String(item.unitPrice));
      data.set(`lineItems[${i}].gstRate`, String(item.gstRate ?? 0.18));
      if (multiAccount && item.accountId) data.set(`lineItems[${i}].accountId`, item.accountId);
    });

    const result = await updatePo(po.id, data);
    if ("error" in result) {
      setError(result.error);
      setSubmitting(null);
    } else {
      router.push(`/po/${result.id}`);
    }
  }

  const poDateValue = po.poDate
    ? new Date(po.poDate).toISOString().split("T")[0]
    : "";
  const dateValue = po.dateRequired
    ? new Date(po.dateRequired).toISOString().split("T")[0]
    : "";
  const piDateValue = po.piQuotationDate
    ? new Date(po.piQuotationDate).toISOString().split("T")[0]
    : "";
  const reqDateValue = po.requisitionDate
    ? new Date(po.requisitionDate).toISOString().split("T")[0]
    : "";

  const extPo = po;

  return (
    <form id="edit-po-form" className="space-y-6" onSubmit={(e) => e.preventDefault()}>
      {canResubmit && (
        <div className="rounded-lg border border-warning-100 bg-warning-50 px-4 py-3">
          <p className="text-sm font-medium text-warning-700">
            {managerNoteAuthor ? `Edits requested by ${managerNoteAuthor}` : "Edits requested"}
          </p>
          {po.managerNote && (
            <p className="mt-1 text-sm text-warning-700 italic">"{po.managerNote}"</p>
          )}
        </div>
      )}

      {/* Order Information */}
      <section className="rounded-lg border border-neutral-200 bg-white p-6">
        <h2 className="text-base font-semibold text-neutral-900 mb-4">Order Information</h2>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          {companies.length > 0 && (
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-1.5">
                Company <span className="text-danger">*</span>
              </label>
              <select name="companyId" required defaultValue={po.companyId ?? ""} className={INPUT_CLS}>
                <option value="">Select company…</option>
                {companies.map((c) => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>
          )}
          <div className={companies.length > 0 ? "" : "sm:col-span-2"}>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">
              Title <span className="text-danger">*</span>
            </label>
            <input name="title" required defaultValue={po.title} className={INPUT_CLS} />
          </div>
          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">
              Cost Centre <span className="text-danger">*</span>
            </label>
            <select name="vesselId" required defaultValue={po.vesselId} className={INPUT_CLS}>
              <option value="">Select cost centre…</option>
              {vessels.map((v) => (
                <option key={v.id} value={v.id}>{v.code} — {v.name}</option>
              ))}
            </select>
          </div>
          <div>
            <div className="flex items-center justify-between mb-1.5">
              <label className="text-sm font-medium text-neutral-700">
                {multiAccount ? "Default Accounting Code" : "Accounting Code"} <span className="text-danger">*</span>
              </label>
              <label className="flex items-center gap-1.5 text-xs text-neutral-500 cursor-pointer select-none">
                <input
                  type="checkbox"
                  checked={multiAccount}
                  onChange={(e) => setMultiAccount(e.target.checked)}
                  className="rounded border-neutral-300"
                />
                Multiple accounts
              </label>
            </div>
            <SearchableSelect
              name="accountId"
              value={defaultAccountId}
              onChange={setDefaultAccountId}
              groups={accounts}
              placeholder="Search accounting code…"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">PO Date</label>
            <input name="poDate" type="date" defaultValue={poDateValue} className={INPUT_CLS} />
            <p className="mt-1 text-xs text-neutral-400">Optional — can be back-dated or forward-dated. Defaults to the approved date if left blank.</p>
          </div>
          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">Project Code</label>
            <input name="projectCode" defaultValue={po.projectCode ?? ""} className={INPUT_CLS} placeholder="Optional" />
          </div>
          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">Delivery Date Required</label>
            <input name="dateRequired" type="date" defaultValue={dateValue} className={INPUT_CLS} />
          </div>
        </div>
      </section>

      {/* Quotation Reference */}
      <section className="rounded-lg border border-neutral-200 bg-white p-6">
        <h2 className="text-base font-semibold text-neutral-900 mb-4">Quotation Reference</h2>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">PI / Quotation No.</label>
            <input name="piQuotationNo" defaultValue={extPo.piQuotationNo ?? ""} className={INPUT_CLS} placeholder='e.g. Verbal, INV-001' />
          </div>
          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">PI / Quotation Date</label>
            <input name="piQuotationDate" type="date" defaultValue={piDateValue} className={INPUT_CLS} />
          </div>
        </div>
      </section>

      {/* Requisition */}
      <section className="rounded-lg border border-neutral-200 bg-white p-6">
        <h2 className="text-base font-semibold text-neutral-900 mb-4">Requisition</h2>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">Cost Centre / Office Requisition No.</label>
            <input name="requisitionNo" defaultValue={extPo.requisitionNo ?? ""} className={INPUT_CLS} placeholder="Optional" />
          </div>
          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">Requisition Date</label>
            <input name="requisitionDate" type="date" defaultValue={reqDateValue} className={INPUT_CLS} />
          </div>
        </div>
      </section>

      {/* Delivery */}
      <section className="rounded-lg border border-neutral-200 bg-white p-6">
        <h2 className="text-base font-semibold text-neutral-900 mb-4">Delivery</h2>
        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-1.5">Place of Delivery</label>
          <textarea name="placeOfDelivery" rows={2} className={INPUT_CLS} defaultValue={extPo.placeOfDelivery ?? ""} />
        </div>
      </section>

      {/* Line Items */}
      <section className="rounded-lg border border-neutral-200 bg-white p-6">
        <h2 className="text-base font-semibold text-neutral-900 mb-4">Line Items</h2>
        <LineItemsEditor
          items={lineItems}
          onChange={setLineItems}
          multiAccount={multiAccount}
          accounts={accounts}
          defaultAccountId={defaultAccountId || undefined}
        />
      </section>

      {/* Vendor */}
      <section className="rounded-lg border border-neutral-200 bg-white p-6">
        <h2 className="text-base font-semibold text-neutral-900 mb-4">Vendor</h2>
        <select name="vendorId" defaultValue={po.vendorId ?? ""} className={INPUT_CLS}>
          <option value="">No vendor selected</option>
          {vendors.map((v) => (
            <option key={v.id} value={v.id}>
              {v.name} {v.vendorId ? `(${v.vendorId})` : "(unverified)"}
            </option>
          ))}
        </select>
      </section>

      {/* Terms & Conditions */}
      <section className="rounded-lg border border-neutral-200 bg-white p-6">
        <h2 className="text-base font-semibold text-neutral-900 mb-4">Terms &amp; Conditions</h2>
        <div className="space-y-3">
          <div className="rounded-lg bg-neutral-50 border border-neutral-200 px-3 py-2.5 text-sm text-neutral-500 select-none">
            <span className="font-medium text-neutral-600">1.</span> {TC_FIXED_LINE}
          </div>
          {([
            { n: 2, label: "Delivery",             name: "tcDelivery",         key: "tcDelivery" },
            { n: 3, label: "Dispatch Instructions", name: "tcDispatch",         key: "tcDispatch" },
            { n: 4, label: "Inspection",            name: "tcInspection",       key: "tcInspection" },
            { n: 5, label: "Transit Insurance",     name: "tcTransitInsurance", key: "tcTransitInsurance" },
            { n: 6, label: "Payment Terms",         name: "tcPaymentTerms",     key: "tcPaymentTerms" },
          ] as const).map(({ n, label, name, key }) => (
            <div key={name} className="flex items-center gap-3">
              <span className="w-5 shrink-0 text-sm font-medium text-neutral-500 text-right">{n}.</span>
              <label className="w-44 shrink-0 text-sm font-medium text-neutral-700">{label}</label>
              <input
                name={name}
                defaultValue={extPo[key] ?? TC_DEFAULTS[key]}
                className={INPUT_CLS}
              />
            </div>
          ))}
          <div className="flex items-start gap-3">
            <span className="w-5 shrink-0 text-sm font-medium text-neutral-500 text-right mt-2.5">7.</span>
            <label className="w-44 shrink-0 text-sm font-medium text-neutral-700 mt-2.5">Others</label>
            <textarea
              name="tcOthers"
              rows={2}
              defaultValue={extPo.tcOthers ?? ""}
              className={INPUT_CLS}
            />
          </div>
          <div className="rounded-lg bg-neutral-50 border border-neutral-200 px-3 py-2.5 text-sm text-neutral-500 select-none">
            <span className="font-medium text-neutral-600">8.</span> {TC_FIXED_LINE_2}
          </div>
        </div>
      </section>

      {error && (
        <p className="text-sm text-danger-700 bg-danger-50 rounded-lg px-3 py-2">{error}</p>
      )}

      <div className="flex items-center gap-3">
        <button type="button" onClick={() => router.back()}
          className="rounded-lg border border-neutral-300 bg-white px-4 py-2.5 text-sm font-medium text-neutral-700 hover:bg-neutral-50 transition-colors">
          Cancel
        </button>
        <button type="button" onClick={() => handleSubmit("save")} disabled={!!submitting}
          className="rounded-lg border border-neutral-300 bg-white px-4 py-2.5 text-sm font-medium text-neutral-700 hover:bg-neutral-50 disabled:opacity-60 transition-colors">
          {submitting === "save" ? "Saving…" : "Save Draft"}
        </button>
        {canSubmit && (
          <button type="button" onClick={() => handleSubmit("submit")} disabled={!!submitting}
            className="rounded-lg bg-primary-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-primary-700 disabled:opacity-60 transition-colors">
            {submitting === "submit" ? "Submitting…" : "Submit for Approval"}
          </button>
        )}
        {canResubmit && (
          <button type="button" onClick={() => handleSubmit("resubmit")} disabled={!!submitting}
            className="rounded-lg bg-primary-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-primary-700 disabled:opacity-60 transition-colors">
            {submitting === "resubmit" ? "Resubmitting…" : "Resubmit for Approval"}
          </button>
        )}
      </div>
    </form>
  );
}
