import { useEffect, useState } from "react";

import { useAuth } from "@/auth/AuthProvider";
import {
  fetchFulfillmentBoard,
  type FulfillmentBoardResponse,
} from "@/api/fulfillment";
import { Card } from "@/components/ui/card";

function fulfillmentStatusClassName(status: string) {
  if (status === "Completed") {
    return "bg-[#dff3ec] text-[var(--in-accent)]";
  }
  if (status === "Blocked") {
    return "bg-[#ffe2d7] text-[#c4663a]";
  }
  if (status === "In progress") {
    return "bg-[#fff0d8] text-[#b56a1f]";
  }

  return "bg-[#efe7d8] text-[var(--in-muted)]";
}

export function FulfillmentPage() {
  const { token } = useAuth();
  const [board, setBoard] = useState<FulfillmentBoardResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!token?.access_token) {
      return;
    }

    let cancelled = false;

    setLoading(true);
    setError(null);

    fetchFulfillmentBoard(token.access_token)
      .then((response) => {
        if (!cancelled) {
          setBoard(response);
        }
      })
      .catch((nextError: Error) => {
        if (!cancelled) {
          setError(nextError.message);
          setBoard(null);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [token?.access_token]);

  return (
    <div className="grid gap-6 xl:grid-cols-[1fr_300px]">
      <Card className="overflow-hidden shadow-[0_18px_48px_rgba(25,54,46,0.06)]">
        <div className="border-b border-[var(--in-border)] px-6 py-5">
          <h2 className="text-xl font-black text-[var(--in-text)]">Fulfillment board</h2>
          <p className="mt-2 text-sm text-[var(--in-muted)]">작업 단위, 담당자, 단계, SLA를 한 번에 보여주는 이행 보드 surface다.</p>
        </div>

        <table className="w-full border-collapse text-sm">
          <thead className="bg-[#faf6ef] text-left text-[var(--in-muted)]">
            <tr>
              {["Order", "Task", "Assignee", "Status", "SLA"].map((cell) => (
                <th key={cell} className="border-b border-[var(--in-border)] px-6 py-4 font-semibold">
                  {cell}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td className="border-b border-[var(--in-border)] px-6 py-4 text-[var(--in-muted)]" colSpan={5}>
                  이행 보드를 불러오는 중입니다.
                </td>
              </tr>
            ) : null}
            {error ? (
              <tr>
                <td className="border-b border-[var(--in-border)] px-6 py-4 text-[#9d4d26]" colSpan={5}>
                  {error}
                </td>
              </tr>
            ) : null}
            {!loading && !error && !(board?.tasks.length ?? 0) ? (
              <tr>
                <td className="border-b border-[var(--in-border)] px-6 py-4 text-[var(--in-muted)]" colSpan={5}>
                  현재 표시할 작업이 없습니다.
                </td>
              </tr>
            ) : null}
            {(board?.tasks ?? []).map((task) => (
              <tr key={task.id}>
                <td className="border-b border-[var(--in-border)] px-6 py-4 font-semibold text-[var(--in-accent)]">{task.order_id}</td>
                <td className="border-b border-[var(--in-border)] px-6 py-4">
                  <div className="font-semibold text-[var(--in-text)]">{task.title}</div>
                  <div className="mt-1 text-xs text-[var(--in-muted)]">
                    {task.stage} · {task.priority}
                  </div>
                </td>
                <td className="border-b border-[var(--in-border)] px-6 py-4 text-[var(--in-muted)]">{task.assignee}</td>
                <td className="border-b border-[var(--in-border)] px-6 py-4">
                  <span className={`rounded-full px-3 py-1 text-xs font-semibold ${fulfillmentStatusClassName(task.status)}`}>{task.status}</span>
                </td>
                <td className="border-b border-[var(--in-border)] px-6 py-4 text-[var(--in-text)]">{task.sla}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <Card className="p-6 shadow-[0_18px_48px_rgba(25,54,46,0.06)]">
        <h2 className="text-xl font-black text-[var(--in-text)]">Fulfillment notes</h2>
        <div className="mt-5 space-y-4">
          {loading ? <div className="text-sm text-[var(--in-muted)]">노트를 불러오는 중입니다.</div> : null}
          {error ? <div className="text-sm font-semibold text-[#9d4d26]">{error}</div> : null}
          {!loading && !error && !(board?.notes.length ?? 0) ? <div className="text-sm text-[var(--in-muted)]">노트가 없습니다.</div> : null}
          {(board?.notes ?? []).map((note) => (
            <div key={note.id} className="rounded-[22px] border border-[var(--in-border)] bg-white px-4 py-4 text-sm leading-6 text-[var(--in-muted)]">
              {note.note}
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}
