import { ArrowLeft, CalendarDays, FileText } from "lucide-react";
import { useNavigate, useParams } from "react-router-dom";
import { Button } from "@/shared/common/ui/button";
import { useRecordDetails } from "@/user-management/all-records/hooks/useAllRecords";

const displayValue = (value?: string | { en?: string; am?: string }) =>
  typeof value === "string" ? value : value?.en || value?.am || "—";

const AllRecordDetailsPage = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const recordQuery = useRecordDetails(id);

  if (recordQuery.isLoading) {
    return <div className="m-6 h-64 animate-pulse rounded-xl bg-slate-200 dark:bg-slate-800" />;
  }
  if (recordQuery.isError || !recordQuery.data) {
    return (
      <div className="m-6 rounded-lg border border-red-200 bg-red-50 p-8 text-center">
        <p className="text-red-700">Unable to load this record.</p>
        <Button variant="outline" className="mt-4" onClick={() => navigate(-1)}>
          Go back
        </Button>
      </div>
    );
  }

  const record = recordQuery.data;
  const fields = [
    ["Reference", record.referenceNumber || "—"],
    ["Subject", displayValue(record.subject)],
    ["Record type", displayValue(record.recordType)],
    ["Sender", displayValue(record.sender)],
    ["Status", record.status || "—"],
    ["Description", record.description || "—"],
  ];

  return (
    <div className="w-full space-y-6 p-4 sm:p-6">
      <Button variant="ghost" className="gap-2" onClick={() => navigate(-1)}>
        <ArrowLeft className="h-4 w-4" /> Back to all records
      </Button>
      <article className="rounded-xl border bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
        <header className="mb-6 border-b pb-5 dark:border-slate-700">
          <h1 className="flex items-center gap-2 text-2xl font-bold">
            <FileText className="h-6 w-6 text-primary" /> Record Details
          </h1>
          <p className="mt-1 text-sm text-slate-500">Record ID: {record.id}</p>
        </header>
        <dl className="grid gap-5 sm:grid-cols-2">
          {fields.map(([label, value]) => (
            <div key={label}>
              <dt className="text-sm text-slate-500">{label}</dt>
              <dd className="mt-1 font-medium">{value}</dd>
            </div>
          ))}
          <div>
            <dt className="flex items-center gap-1 text-sm text-slate-500">
              <CalendarDays className="h-4 w-4" /> Created
            </dt>
            <dd className="mt-1 font-medium">
              {record.createdAt
                ? new Date(record.createdAt).toLocaleString()
                : "—"}
            </dd>
          </div>
        </dl>
      </article>
    </div>
  );
};

export default AllRecordDetailsPage;
