import { AppShell } from "@/components/AppShell";
import { DeleteButton } from "@/components/DeleteButton";
import { EmptyState } from "@/components/EmptyState";
import { PageHeader } from "@/components/PageHeader";
import { StatusMessage } from "@/components/StatusMessage";
import {
  createCategoryAction,
  createDocumentCategoryAction,
  deleteProjectScopedRecordAction,
  updateCategoryAction,
  updateDocumentCategoryAction
} from "@/app/actions";
import { getSelectedProject } from "@/lib/projects";

export default async function CategoriesPage({
  searchParams
}: {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = (await searchParams) ?? {};
  const selected = typeof params.projectId === "string" ? params.projectId : undefined;
  const { user, projects, project, permissions, projectRole } = await getSelectedProject(selected, "categories.view");
  const canEdit = Boolean(permissions?.["categories.create"] || permissions?.["categories.edit"] || permissions?.["categories.archive"] || permissions?.["categories.delete"]);

  if (!project) {
    return (
      <AppShell projects={projects} username={user.name ?? user.username ?? user.email} role={projectRole ?? user.role} permissions={permissions}>
        <EmptyState title="Create a project before managing categories." href="/projects" actionLabel="Create project" />
      </AppShell>
    );
  }

  return (
    <AppShell projects={projects} selectedProjectId={project.id} username={user.name ?? user.username ?? user.email} role={projectRole ?? user.role} permissions={permissions}>
      <PageHeader title="Categories" description="Customize finance categories and document cabinet categories." />
      <StatusMessage updated={params.updated} deleted={params.deleted} error={params.error} />
      <section className="grid gap-6 xl:grid-cols-[0.8fr_1.2fr]">
        {canEdit ? (
          <form action={createCategoryAction} className="panel grid gap-4 p-4">
            <h3 className="font-semibold text-ink">New Category</h3>
            <input type="hidden" name="projectId" value={project.id} />
            <label className="grid gap-2">
              <span className="label">Name</span>
              <input className="field" name="name" required />
            </label>
            <label className="grid gap-2">
              <span className="label">Type</span>
              <select className="field" name="type" defaultValue="RENOVATION_EXPENSE">
                <option value="PURCHASE_COST">Purchase cost</option>
                <option value="RENOVATION_EXPENSE">Renovation expense</option>
                <option value="OPERATING_EXPENSE">Operating expense</option>
                <option value="RENTAL_INCOME">Rental income</option>
                <option value="OTHER_INCOME">Other income</option>
              </select>
            </label>
            <button className="btn-primary">Create category</button>
          </form>
        ) : null}

        <div className="panel overflow-hidden">
          <div className="border-b border-line px-4 py-3">
            <h3 className="font-semibold text-ink">Category List</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="table-head">
                <tr>
                  <th className="px-3 py-2">Name</th>
                  <th className="px-3 py-2">Type</th>
                  {canEdit ? <th className="px-3 py-2">Actions</th> : null}
                </tr>
              </thead>
              <tbody>
                {project.categories.map((category) => (
                  <tr key={category.id}>
                    <td className="table-cell font-medium text-ink">{category.name}</td>
                    <td className="table-cell">{category.type.toLowerCase().replaceAll("_", " ")}</td>
                    {canEdit ? (
                      <td className="table-cell align-top">
                        <div className="flex flex-wrap gap-2">
                          <details className="action-modal">
                            <summary>Edit</summary>
                            <form action={updateCategoryAction} className="mt-3 grid min-w-72 gap-3">
                              <input type="hidden" name="projectId" value={project.id} />
                              <input type="hidden" name="categoryId" value={category.id} />
                              <input className="field" name="name" defaultValue={category.name} required />
                              <select className="field" name="type" defaultValue={category.type}>
                                <option value="PURCHASE_COST">Purchase cost</option>
                                <option value="RENOVATION_EXPENSE">Renovation expense</option>
                                <option value="OPERATING_EXPENSE">Operating expense</option>
                                <option value="RENTAL_INCOME">Rental income</option>
                                <option value="OTHER_INCOME">Other income</option>
                              </select>
                              <label className="flex items-center gap-2 text-sm text-slate-700">
                                <input name="archived" type="checkbox" defaultChecked={category.archived} className="h-4 w-4 rounded border-line" />
                                Archived
                              </label>
                              <button className="btn-primary">Update category</button>
                            </form>
                          </details>
                          <form action={deleteProjectScopedRecordAction}>
                            <input type="hidden" name="projectId" value={project.id} />
                            <input type="hidden" name="model" value="category" />
                            <input type="hidden" name="id" value={category.id} />
                            <input type="hidden" name="returnTo" value="/settings/categories" />
                            <DeleteButton label="Archive or delete category" message={`Archive or delete category ${category.name}? Used categories will be archived so old records keep their label.`} />
                          </form>
                        </div>
                      </td>
                    ) : null}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </section>

      <section className="mt-6 grid gap-6 xl:grid-cols-[0.8fr_1.2fr]">
        {canEdit ? (
          <form action={createDocumentCategoryAction} className="panel grid gap-4 p-4">
            <h3 className="font-semibold text-ink">New Document Category</h3>
            <input type="hidden" name="projectId" value={project.id} />
            <label className="grid gap-2">
              <span className="label">Name</span>
              <input className="field" name="name" required />
            </label>
            <button className="btn-primary">Create document category</button>
          </form>
        ) : null}

        <div className="panel overflow-hidden">
          <div className="border-b border-line px-4 py-3">
            <h3 className="font-semibold text-ink">Document Category List</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="table-head">
                <tr>
                  <th className="px-3 py-2">Name</th>
                  <th className="px-3 py-2">Status</th>
                  {canEdit ? <th className="px-3 py-2">Actions</th> : null}
                </tr>
              </thead>
              <tbody>
                {project.documentCategories.map((category) => (
                  <tr key={category.id}>
                    <td className="table-cell font-medium text-ink">{category.name}</td>
                    <td className="table-cell">{category.archived ? "Archived" : "Active"}</td>
                    {canEdit ? (
                      <td className="table-cell align-top">
                        <div className="flex flex-wrap gap-2">
                          <details className="action-modal">
                            <summary>Edit</summary>
                            <form action={updateDocumentCategoryAction} className="mt-3 grid min-w-72 gap-3">
                              <input type="hidden" name="projectId" value={project.id} />
                              <input type="hidden" name="documentCategoryId" value={category.id} />
                              <input className="field" name="name" defaultValue={category.name} required />
                              <label className="flex items-center gap-2 text-sm text-slate-700">
                                <input name="archived" type="checkbox" defaultChecked={category.archived} className="h-4 w-4 rounded border-line" />
                                Archived
                              </label>
                              <button className="btn-primary">Update document category</button>
                            </form>
                          </details>
                          <form action={deleteProjectScopedRecordAction}>
                            <input type="hidden" name="projectId" value={project.id} />
                            <input type="hidden" name="model" value="documentCategory" />
                            <input type="hidden" name="id" value={category.id} />
                            <input type="hidden" name="returnTo" value="/settings/categories" />
                            <DeleteButton label="Archive or delete category" message={`Archive or delete document category ${category.name}? Used categories will be archived so old documents keep their label.`} />
                          </form>
                        </div>
                      </td>
                    ) : null}
                  </tr>
                ))}
              </tbody>
            </table>
            {project.documentCategories.length === 0 ? (
              <div className="p-6 text-sm text-slate-600">No document categories yet.</div>
            ) : null}
          </div>
        </div>
      </section>
    </AppShell>
  );
}
