"use client";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  PageHeader,
  Panel,
  DetailList,
  StatusBadge,
  PreviewNotice,
} from "@/components/shared/page";
import { DataTable } from "@/components/shared/data-table";
import { Tabs } from "@/components/shared/tabs";
import {
  usePreviewRole,
  PreviewLink,
} from "@/components/layout/preview-context";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { canManage } from "@/lib/preview";
import { locations } from "@/features/locations/fixtures";
import { ContractForm } from "./contract-form";
import { Participants } from "./participants";
import { Deductions } from "./deductions";
import { Settlements } from "./settlements";
import { emptyContract } from "./fixtures";
import {
  contractTypes,
  contractTypeLabels,
  type BusinessContract,
} from "./model";
import { useContracts } from "./store";
function ContractAccess() {
  return (
    <Panel title="Business Contracts">
      <div className="space-y-3 p-5">
        <p className="text-sm text-muted-foreground">
          Business contract administration is available in the Admin preview.
        </p>
        <PreviewLink href="/locations" className="text-sm text-primary">
          View assigned locations and financial reports →
        </PreviewLink>
      </div>
    </Panel>
  );
}
export function ContractList() {
  const role = usePreviewRole(),
    router = useRouter();
  const { contracts } = useContracts();
  return (
    <div className="space-y-5">
      <PageHeader title="Business Contracts" />
      {!canManage(role) ? (
        <ContractAccess />
      ) : (
        <>
          <PreviewNotice>
            Contract administration uses local fixtures. Changes stay in this
            browser session.
          </PreviewNotice>
          <DataTable
            title="Business Contracts"
            description="Manage revenue sharing, fixed cost agreements, and settlements."
            rows={contracts}
            columns={[
              {
                key: "name",
                label: "Contract Name",
                render: (row) => (
                  <PreviewLink
                    className="text-primary hover:underline"
                    href={`/reports/business-contracts/${row.id}`}
                  >
                    {row.name}
                  </PreviewLink>
                ),
              },
              { key: "code", label: "Code" },
              {
                key: "type",
                label: "Contract Type",
                render: (row) => contractTypeLabels[row.type],
              },
              {
                key: "status",
                label: "Status",
                render: (row) => <StatusBadge>{row.status}</StatusBadge>,
              },
              { key: "currency", label: "Currency" },
              {
                key: "start",
                label: "Period",
                render: (row) => `${row.start} → ${row.end || "Ongoing"}`,
              },
              { key: "updated", label: "Last Updated" },
            ]}
            filters={[
              {
                key: "status",
                label: "Status",
                options: ["DRAFT", "ACTIVE", "ENDED"],
              },
              { key: "type", label: "Contract Type", options: contractTypes },
            ]}
            onCreate={() =>
              router.push(`/reports/business-contracts/new?role=${role}`)
            }
            createLabel="Create Contract"
            actions={(row) => (
              <PreviewLink
                href={`/reports/business-contracts/${row.id}`}
                className="text-primary"
              >
                View
              </PreviewLink>
            )}
          />
        </>
      )}
    </div>
  );
}
export function ContractCreate() {
  const role = usePreviewRole(),
    router = useRouter();
  const { contracts, save } = useContracts();
  return (
    <div className="space-y-5">
      <PageHeader
        title="Create Business Contract"
        parent={{
          label: "Business Contracts",
          href: "/reports/business-contracts",
        }}
      />
      {!canManage(role) ? (
        <ContractAccess />
      ) : (
        <ContractForm
          initial={{ ...emptyContract }}
          existing={contracts}
          onCancel={() =>
            router.push(`/reports/business-contracts?role=${role}`)
          }
          onSave={(row) => {
            save(row);
            router.push(`/reports/business-contracts/${row.id}?role=${role}`);
          }}
        />
      )}
    </div>
  );
}
export function ContractDetail({ id }: { id: string }) {
  const role = usePreviewRole(),
    params = useSearchParams(),
    router = useRouter();
  const { contracts, save, remove } = useContracts();
  const contract = contracts.find((row) => row.id === id);
  const [editing, setEditing] = useState(false),
    [deleting, setDeleting] = useState(false),
    [notice, setNotice] = useState("");
  const requested = params.get("tab"),
    tab = ["participants", "deductions", "settlements"].includes(
      requested ?? "",
    )
      ? requested
      : "overview";
  const update = (next: BusinessContract) => {
    save({ ...next, updated: "2026-10-15" });
    setNotice("Contract preview saved for this browser session.");
  };
  if (!canManage(role))
    return (
      <>
        <PageHeader title="Business Contracts" />
        <ContractAccess />
      </>
    );
  if (!contract)
    return (
      <>
        <PageHeader title="Business Contract" />
        <Panel title="Contract not found">
          <div className="space-y-3 p-5">
            <p className="text-sm text-muted-foreground">
              This contract is not available in the local preview.
            </p>
            <PreviewLink
              className="text-primary"
              href="/reports/business-contracts"
            >
              Back to Business Contracts
            </PreviewLink>
          </div>
        </Panel>
      </>
    );
  return (
    <div className="space-y-5">
      <PageHeader
        title={contract.name}
        parent={{
          label: "Business Contracts",
          href: "/reports/business-contracts",
        }}
      />
      {notice && <PreviewNotice>{notice}</PreviewNotice>}
      {editing ? (
        <ContractForm
          key={contract.id}
          initial={contract}
          existing={contracts}
          onCancel={() => setEditing(false)}
          onSave={(row) => {
            update(row);
            setEditing(false);
          }}
        />
      ) : (
        <>
          <div className="flex flex-wrap justify-between gap-4">
            <Tabs
              items={[
                { value: "overview", label: "Contract Overview" },
                {
                  value: "participants",
                  label: `Participants (${contract.participants.length})`,
                },
                {
                  value: "deductions",
                  label: `Deductions (${contract.deductions.length})`,
                },
                {
                  value: "settlements",
                  label: `Settlements (${contract.settlements.length})`,
                },
              ]}
            />
            <div className="flex gap-2">
              <Button variant="outline" onClick={() => setEditing(true)}>
                Edit Contract
              </Button>
              <Button variant="destructive" onClick={() => setDeleting(true)}>
                Delete Contract
              </Button>
            </div>
          </div>
          {tab === "overview" && (
            <>
              <Panel title="Contract Information">
                <DetailList
                  items={{
                    "Contract Name": contract.name,
                    Code: contract.code,
                    Organization: contract.organization,
                    "Contract Type": contractTypeLabels[contract.type],
                    Status: <StatusBadge>{contract.status}</StatusBadge>,
                    Currency: contract.currency,
                    "Start Date": contract.start,
                    "End Date": contract.end || "Ongoing",
                    "Settlement Cycle": contract.cycle,
                    "Settlement Lag": `${contract.lag} days`,
                    Priority: contract.priority,
                    "Reference Contract PDF":
                      contract.reference || "No document selected",
                    "Display BM Share VAT": contract.displayVat ? "Yes" : "No",
                  }}
                />
              </Panel>
              <Panel title="Location Scopes">
                <div className="grid gap-4 p-5 sm:grid-cols-2">
                  {contract.locationIds.map((locationId) => {
                    const location = locations.find(
                      (row) => row.id === locationId,
                    );
                    return (
                      <PreviewLink
                        key={locationId}
                        href={`/locations/${locationId}`}
                        className="rounded-lg border p-4 hover:border-primary"
                      >
                        <p className="font-medium">
                          {location?.name ?? locationId}
                        </p>
                        <p className="mt-1 text-sm text-muted-foreground">
                          {location?.city}
                        </p>
                      </PreviewLink>
                    );
                  })}
                </div>
              </Panel>
              <PreviewNotice>
                Use Participants to manage terms and Settlements to preview
                payment allocation.
              </PreviewNotice>
            </>
          )}
          {tab === "participants" && (
            <Participants
              participants={contract.participants}
              onChange={(participants) => update({ ...contract, participants })}
            />
          )}{" "}
          {tab === "deductions" && (
            <Deductions
              deductions={contract.deductions}
              onChange={(deductions) => update({ ...contract, deductions })}
            />
          )}{" "}
          {tab === "settlements" && (
            <Settlements
              contract={contract}
              onChange={(settlements) => update({ ...contract, settlements })}
            />
          )}
        </>
      )}
      <Dialog open={deleting} onOpenChange={setDeleting}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Business Contract</DialogTitle>
            <DialogDescription>
              Remove {contract.name}, its participants, terms, and settlement
              previews from this browser session?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleting(false)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => {
                remove(contract.id);
                router.push(`/reports/business-contracts?role=${role}`);
              }}
            >
              Delete Contract Preview
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
