import Link from "next/link";
import { GROUPS, SPECIALTIES, STAGES, stageById, serviceLabel } from "@/lib/catalog";
import { searchCases, type CaseFilters } from "@/lib/cases";
import { faNum, formatDay } from "@/lib/format";

export const metadata = { title: "پرونده‌ها" };

function one(value: string | string[] | undefined) {
  const raw = Array.isArray(value) ? value[0] : value;
  return raw?.trim() ?? "";
}

function mainService(json: string) {
  const ids = JSON.parse(json) as string[];
  if (!ids.length) return "ندارد";
  const first = serviceLabel(ids[0]);
  if (ids.length === 1) return first;
  return `${first} و ${faNum(ids.length - 1)} مورد دیگر`;
}

const languages: Record<string, string> = { fa: "فارسی", en: "English", ar: "العربية" };

export default async function CasesPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const sp = await searchParams;
  const filters: CaseFilters = {
    q: one(sp.q),
    groupId: one(sp.groupId),
    specialtyId: one(sp.specialtyId),
    stageId: one(sp.stageId),
    language: one(sp.language),
    arrivedFrom: one(sp.arrivedFrom),
    arrivedTo: one(sp.arrivedTo),
    departedFrom: one(sp.departedFrom),
    departedTo: one(sp.departedTo),
  };
  const rows = searchCases(filters);
  const grouped = GROUPS.map((group) => ({
    group,
    specialties: SPECIALTIES.filter((item) => item.groupId === group.id)
      .map((specialty) => ({
        specialty,
        rows: rows.filter((row) => row.specialty_id === specialty.id),
      }))
      .filter((item) => item.rows.length > 0),
  })).filter((group) => group.specialties.length > 0);

  return (
    <div className="stack">
      <section className="card stack">
        <div className="group-head">
          <h1>پرونده‌ها</h1>
          <Link className="button" href="/staff/cases/new">پرونده جدید</Link>
        </div>
        <p className="hint">فهرست بر اساس تخصص گروه‌بندی شده است. هر گروه تعداد پرونده را نشان می‌دهد.</p>
        <form method="get" className="fields filters">
          <label>
            نام یا موبایل
            <input name="q" defaultValue={filters.q} placeholder="نام، موبایل یا شماره پرونده" />
          </label>
          <label>
            گروه
            <select name="groupId" defaultValue={filters.groupId}>
              <option value="">همه</option>
              {GROUPS.map((group) => (
                <option key={group.id} value={group.id}>{group.fa}</option>
              ))}
            </select>
          </label>
          <label>
            تخصص
            <select name="specialtyId" defaultValue={filters.specialtyId}>
              <option value="">همه</option>
              {SPECIALTIES.map((specialty) => (
                <option key={specialty.id} value={specialty.id}>{specialty.fa}</option>
              ))}
            </select>
          </label>
          <label>
            مرحله فعلی
            <select name="stageId" defaultValue={filters.stageId}>
              <option value="">همه</option>
              {STAGES.map((stage) => (
                <option key={stage.id} value={stage.id}>{stage.title.fa}</option>
              ))}
            </select>
          </label>
          <label>
            زبان
            <select name="language" defaultValue={filters.language}>
              <option value="">همه</option>
              <option value="fa">فارسی</option>
              <option value="en">English</option>
              <option value="ar">العربية</option>
            </select>
          </label>
          <label>
            ورود از
            <input name="arrivedFrom" type="date" defaultValue={filters.arrivedFrom} />
          </label>
          <label>
            ورود تا
            <input name="arrivedTo" type="date" defaultValue={filters.arrivedTo} />
          </label>
          <label>
            خروج از
            <input name="departedFrom" type="date" defaultValue={filters.departedFrom} />
          </label>
          <label>
            خروج تا
            <input name="departedTo" type="date" defaultValue={filters.departedTo} />
          </label>
          <div className="toolbar">
            <button type="submit">اعمال فیلتر</button>
            <Link className="button secondary" href="/staff/cases">پاک کردن فیلتر</Link>
          </div>
        </form>
      </section>

      <p className="muted">{faNum(rows.length)} پرونده</p>
      {grouped.length === 0 ? (
        <section className="card"><p>پرونده‌ای با این فیلتر پیدا نشد.</p></section>
      ) : null}

      {grouped.map((group) =>
        group.specialties.map((item) => (
          <section className="card" key={item.specialty.id}>
            <div className="group-head">
              <h2>{item.specialty.fa} ({item.specialty.en})</h2>
              <span className="count">{group.group.fa} · {faNum(item.rows.length)} پرونده</span>
            </div>
            <div className="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>شماره</th>
                    <th>نام</th>
                    <th>خدمت اصلی</th>
                    <th>مرحله فعلی</th>
                    <th>ورود</th>
                    <th>خروج</th>
                    <th>زبان</th>
                  </tr>
                </thead>
                <tbody>
                  {item.rows.map((row) => (
                    <tr key={row.id}>
                      <td><Link href={`/staff/cases/${row.id}`}>{row.case_number}</Link></td>
                      <td><Link href={`/staff/cases/${row.id}`}>{row.first_name} {row.last_name}</Link></td>
                      <td>{mainService(row.requested_services)}</td>
                      <td>{stageById(row.current_stage_id || "")?.title.fa ?? "ندارد"}</td>
                      <td>{formatDay(row.arrived_iran_on, "fa") || "ندارد"}</td>
                      <td>{formatDay(row.departed_iran_on, "fa") || "ندارد"}</td>
                      <td>{languages[row.language] ?? row.language}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )),
      )}
    </div>
  );
}
