import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { SEX_LABELS, sexColors } from "@/lib/sex";
import { getCurrentUser, isSubscriptionActive } from "@/lib/auth";
import { getSort, SortableHeader } from "@/components/SortableHeader";
import { Prisma, type HorseStatus, type Sex } from "@/generated/prisma/client";

const SORT_FIELDS = ["name", "sex", "status", "foundation"] as const;

function horseOrderBy(field: string, dir: "asc" | "desc"): Prisma.HorseOrderByWithRelationInput | Prisma.HorseOrderByWithRelationInput[] {
  switch (field) {
    case "name":
      return [{ registeredName: dir }, { barnName: dir }];
    case "sex":
      return { sex: dir };
    case "status":
      return { status: dir };
    case "foundation":
      return { foundationPercentage: dir };
    default:
      return { createdAt: "desc" };
  }
}

const HORSE_STATUS_LABELS: Record<string, string> = {
  ACTIVE: "Active",
  FOR_SALE: "For Sale",
  LEASED: "Leased",
  RETIRED: "Retired",
  DECEASED: "Deceased",
  SOLD: "Sold",
};

export default async function HorsesPage(props: PageProps<"/horses">) {
  const sp = await props.searchParams;
  const q = typeof sp.q === "string" ? sp.q.trim() : "";
  const statusFilter = typeof sp.status === "string" ? sp.status : "";
  const sexFilter = typeof sp.sex === "string" ? sp.sex : "";
  const { field: sortField, dir: sortDir } = getSort(sp, SORT_FIELDS);

  const horses = await prisma.horse.findMany({
    where: {
      AND: [
        statusFilter ? { status: statusFilter as HorseStatus } : {},
        sexFilter ? { sex: sexFilter as Sex } : {},
        q
          ? {
              OR: [
                { barnName: { contains: q } },
                { registeredName: { contains: q } },
                { breed: { contains: q } },
                { registrationNumber: { contains: q } },
                { tags: { some: { name: { contains: q } } } },
              ],
            }
          : {},
      ],
    },
    include: { tags: true },
    orderBy: horseOrderBy(sortField, sortDir),
  });

  const currentUser = await getCurrentUser();
  const canCreate = !!currentUser && (currentUser.role === "ADMIN" || isSubscriptionActive(currentUser));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold">Horses</h1>
        {canCreate && (
          <Link href="/horses/new" className="rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-4 py-2 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
            + Add Horse
          </Link>
        )}
        {currentUser?.role === "BREEDER" && !canCreate && (
          <Link href="/account/renew" className="text-sm text-amber-700 dark:text-amber-300 hover:underline">
            Renew your account to add horses
          </Link>
        )}
      </div>

      <form method="GET" className="flex flex-wrap gap-2">
        <input
          type="text"
          name="q"
          defaultValue={q}
          placeholder="Search name, breed, registration, tag..."
          className="w-full max-w-sm rounded-md border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 px-3 py-2 text-sm text-neutral-900 dark:text-neutral-200 focus:border-neutral-500 focus:dark:border-neutral-400 focus:outline-none"
        />
        <select
          name="sex"
          defaultValue={sexFilter}
          className="rounded-md border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 px-3 py-2 text-sm text-neutral-900 dark:text-neutral-200 focus:border-neutral-500 focus:dark:border-neutral-400 focus:outline-none"
        >
          <option value="">All sexes</option>
          {Object.entries(SEX_LABELS).map(([value, label]) => (
            <option key={value} value={value}>{label}</option>
          ))}
        </select>
        <select
          name="status"
          defaultValue={statusFilter}
          className="rounded-md border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 px-3 py-2 text-sm text-neutral-900 dark:text-neutral-200 focus:border-neutral-500 focus:dark:border-neutral-400 focus:outline-none"
        >
          <option value="">All statuses</option>
          {Object.entries(HORSE_STATUS_LABELS).map(([value, label]) => (
            <option key={value} value={value}>{label}</option>
          ))}
        </select>
        <button type="submit" className="rounded-md border border-neutral-300 dark:border-neutral-700 px-4 py-2 text-sm font-medium hover:bg-neutral-50 hover:dark:bg-neutral-950">
          Filter
        </button>
        {(q || statusFilter || sexFilter) && (
          <Link href="/horses" className="rounded-md border border-neutral-300 dark:border-neutral-700 px-4 py-2 text-sm font-medium hover:bg-neutral-50 hover:dark:bg-neutral-950">
            Clear
          </Link>
        )}
      </form>

      {horses.length === 0 ? (
        <p className="text-neutral-700 dark:text-neutral-300">
          {q || statusFilter || sexFilter ? "No horses match your search." : "No horses yet. Add your first horse profile to get started."}
        </p>
      ) : (
        <>
          <ul className="space-y-2 sm:hidden">
            {horses.map((horse) => (
              <li key={horse.id}>
                <Link
                  href={`/horses/${horse.id}`}
                  className="block rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-4 active:bg-neutral-50 active:dark:bg-neutral-950"
                >
                  <div className="flex items-center justify-between gap-2">
                    <span className="font-medium">{horse.registeredName || horse.barnName || "Unnamed Horse"}</span>
                    <span
                      className={`shrink-0 rounded-full border px-2 py-0.5 text-xs font-medium ${sexColors(horse.sex).bg} ${sexColors(horse.sex).border} ${sexColors(horse.sex).text}`}
                    >
                      {SEX_LABELS[horse.sex] ?? horse.sex}
                    </span>
                  </div>
                  <div className="mt-1 text-sm text-neutral-700 dark:text-neutral-300">
                    {horse.status.replace("_", " ")}
                    {horse.foundationPercentage != null ? ` · ${horse.foundationPercentage}% foundation` : ""}
                    {currentUser && horse.currentOwnerId === currentUser.id && (
                      <span className="ml-2 rounded-full border border-sky-300 dark:border-sky-700 bg-sky-100 dark:bg-sky-900 px-2 py-0.5 text-xs font-medium text-sky-800 dark:text-sky-300">
                        Yours
                      </span>
                    )}
                  </div>
                  {horse.tags.length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-1">
                      {horse.tags.map((tag) => (
                        <span key={tag.id} className="rounded-full bg-neutral-100 dark:bg-neutral-900 px-2 py-0.5 text-xs text-neutral-800 dark:text-neutral-300">
                          {tag.name}
                        </span>
                      ))}
                    </div>
                  )}
                </Link>
              </li>
            ))}
          </ul>

          <div className="hidden overflow-x-auto rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 sm:block">
            <table className="w-full text-left text-sm">
              <thead className="bg-neutral-50 dark:bg-neutral-950 text-neutral-700 dark:text-neutral-300">
                <tr>
                  <SortableHeader pathname="/horses" sp={sp} field="name" label="Name" activeField={sortField} activeDir={sortDir} />
                  <SortableHeader pathname="/horses" sp={sp} field="sex" label="Sex" activeField={sortField} activeDir={sortDir} />
                  <SortableHeader pathname="/horses" sp={sp} field="status" label="Status" activeField={sortField} activeDir={sortDir} />
                  <SortableHeader pathname="/horses" sp={sp} field="foundation" label="Foundation %" activeField={sortField} activeDir={sortDir} />
                  <th className="px-4 py-3 font-medium">Tags</th>
                </tr>
              </thead>
              <tbody>
                {horses.map((horse) => (
                  <tr key={horse.id} className="border-t border-neutral-100 dark:border-neutral-800 hover:bg-neutral-50 hover:dark:bg-neutral-950">
                    <td className="px-4 py-3">
                      <Link href={`/horses/${horse.id}`} className="font-medium hover:underline">
                        {horse.registeredName || horse.barnName || "Unnamed Horse"}
                      </Link>
                      {currentUser && horse.currentOwnerId === currentUser.id && (
                        <span className="ml-2 rounded-full border border-sky-300 dark:border-sky-700 bg-sky-100 dark:bg-sky-900 px-2 py-0.5 text-xs font-medium text-sky-800 dark:text-sky-300">
                          Yours
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={`rounded-full border px-2 py-0.5 text-xs font-medium ${sexColors(horse.sex).bg} ${sexColors(horse.sex).border} ${sexColors(horse.sex).text}`}
                      >
                        {SEX_LABELS[horse.sex] ?? horse.sex}
                      </span>
                    </td>
                    <td className="px-4 py-3">{horse.status.replace("_", " ")}</td>
                    <td className="px-4 py-3">
                      {horse.foundationPercentage != null ? `${horse.foundationPercentage}%` : "—"}
                      {horse.foundationPercentage != null && (
                        <span className="ml-1 text-xs text-neutral-600 dark:text-neutral-400">
                          ({horse.foundationPercentageSource === "AUTO" ? "auto" : "manual"})
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex flex-wrap gap-1">
                        {horse.tags.map((tag) => (
                          <span key={tag.id} className="rounded-full bg-neutral-100 dark:bg-neutral-900 px-2 py-0.5 text-xs text-neutral-800 dark:text-neutral-300">
                            {tag.name}
                          </span>
                        ))}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}
