import Image from "next/image";
import { formatDate } from "@/lib/format";
import { TYPE_LABELS, stageInfo } from "@/lib/custom-orders";
import { advanceCustomOrderStatus, cancelCustomOrderRequest, uploadDesignProof } from "@/lib/actions/custom-orders";
import ScrollableTable from "@/components/admin/ScrollableTable";

type Row = {
  id: string;
  customerName: string;
  phone: string;
  type: string;
  quantity: number | null;
  details: string;
  referenceImage: string | null;
  status: string;
  createdAt: Date;
  designProofImage?: string | null;
  customerFeedback?: string | null;
};

export default function CustomOrderTable({ requests, returnTo }: { requests: Row[]; returnTo: string }) {
  if (requests.length === 0) {
    return <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">Nothing here yet.</p>;
  }

  return (
    <ScrollableTable>
      <table className="w-full min-w-[1100px] text-sm">
        <thead className="sticky top-0 z-10 bg-rose-50 text-left text-xs uppercase text-stone-500">
          <tr>
            <th className="p-3">Customer</th>
            <th className="p-3">Type</th>
            <th className="p-3">Qty</th>
            <th className="p-3">Details</th>
            <th className="p-3">Image</th>
            <th className="p-3">Status</th>
            <th className="p-3">Requested</th>
            <th className="p-3">Actions</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-rose-100">
          {requests.map((r) => {
            const stage = stageInfo(r.status);
            return (
              <tr key={r.id}>
                <td className="whitespace-nowrap p-3">
                  <p className="font-medium text-stone-800">{r.customerName}</p>
                  <p className="text-xs text-stone-500">{r.phone}</p>
                </td>
                <td className="whitespace-nowrap p-3 text-stone-600">{TYPE_LABELS[r.type] ?? r.type}</td>
                <td className="whitespace-nowrap p-3 text-stone-600">{r.quantity ?? "—"}</td>
                <td className="max-w-xs p-3 text-stone-600">{r.details}</td>
                <td className="whitespace-nowrap p-3">
                  {r.referenceImage ? (
                    <a href={r.referenceImage} target="_blank" rel="noopener noreferrer">
                      <Image src={r.referenceImage} alt="Reference" width={40} height={40} className="rounded object-cover" />
                    </a>
                  ) : (
                    <span className="text-stone-400">—</span>
                  )}
                </td>
                <td className="whitespace-nowrap p-3">
                  <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${stage.color}`}>{stage.label}</span>
                </td>
                <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(r.createdAt)}</td>
                <td className="p-3">
                  <div className="flex items-center gap-2">
                    {stage.next && (
                      <form action={advanceCustomOrderStatus.bind(null, r.id, stage.next, returnTo)}>
                        <button type="submit" className="rounded-md bg-rose-700 px-2 py-1 text-xs font-medium text-white hover:bg-rose-800">
                          {stage.nextLabel}
                        </button>
                      </form>
                    )}
                    {stage.next && (
                      <form action={cancelCustomOrderRequest.bind(null, r.id, returnTo)}>
                        <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                          Cancel
                        </button>
                      </form>
                    )}
                  </div>
                  {r.status === "design_approval" && (
                    <div className="mt-2 min-w-[220px] rounded-md border border-sky-100 bg-sky-50/60 p-2">
                      {r.designProofImage ? (
                        <div className="flex items-center gap-2">
                          <a href={r.designProofImage} target="_blank" rel="noopener noreferrer">
                            <Image src={r.designProofImage} alt="Design proof" width={32} height={32} className="rounded object-cover" />
                          </a>
                          <span className="text-xs text-stone-500">
                            {r.customerFeedback ? "Awaiting a new proof — customer asked for changes" : "Waiting on customer response"}
                          </span>
                        </div>
                      ) : (
                        <span className="text-xs text-stone-500">No proof uploaded yet</span>
                      )}
                      {r.customerFeedback && (
                        <p className="mt-1 text-xs text-amber-700">&ldquo;{r.customerFeedback}&rdquo;</p>
                      )}
                      <form action={uploadDesignProof.bind(null, r.id)} className="mt-1 flex items-center gap-1">
                        <input type="file" name="image" accept="image/jpeg,image/png,image/webp,image/gif" required className="w-full text-xs" />
                        <button type="submit" className="whitespace-nowrap rounded-md bg-sky-700 px-2 py-1 text-xs font-medium text-white hover:bg-sky-800">
                          Upload proof
                        </button>
                      </form>
                    </div>
                  )}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </ScrollableTable>
  );
}
