"use client";

import { useState } from "react";
import Link from "next/link";
import { trpc } from "~/lib/trpc/client.js";
import { useDebounce } from "~/hooks/useDebounce.js";
import { SortableColumnHeader } from "~/components/ui/SortableColumnHeader.js";
import { useTableSort } from "~/hooks/useTableSort.js";
import { ProficiencyBadge, PROFICIENCY_LABELS, formatDate } from "./shared.js";

export function SearchTab() {
  const [searchSkill, setSearchSkill] = useState("");
  const [minProficiency, setMinProficiency] = useState(1);
  const [availableOnly, setAvailableOnly] = useState(false);

  const debouncedSearch = useDebounce(searchSkill, 300);

  const { data, isLoading } = trpc.resource.getSkillMarketplace.useQuery(
    { searchSkill: debouncedSearch || undefined, minProficiency, availableOnly },
    { staleTime: 30_000, enabled: debouncedSearch.trim().length > 0 },
  );

  const { sorted, sortField, sortDir, toggle } = useTableSort(data?.searchResults ?? []);

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="bg-white dark:bg-slate-900 rounded-xl border border-gray-200 dark:border-slate-700 p-5 space-y-4">
        <div className="flex flex-wrap gap-3 items-center">
          {/* Search input */}
          <div className="relative">
            <svg
              className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"
              fill="none" viewBox="0 0 24 24" stroke="currentColor"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0z" />
            </svg>
            <input
              type="text"
              placeholder="Search by skill name..."
              value={searchSkill}
              onChange={(e) => setSearchSkill(e.target.value)}
              className="pl-8 pr-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg text-sm bg-white dark:bg-slate-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-500 w-60"
            />
          </div>

          {/* Min proficiency */}
          <div className="flex items-center gap-1.5">
            <span className="text-xs text-gray-500 dark:text-gray-400">Min. proficiency:</span>
            <div className="flex rounded-lg overflow-hidden border border-gray-200 dark:border-slate-600">
              {[1, 2, 3, 4, 5].map((lvl) => (
                <button
                  key={lvl}
                  type="button"
                  title={PROFICIENCY_LABELS[lvl]}
                  onClick={() => setMinProficiency(lvl)}
                  className={`px-2 py-1 text-xs font-medium transition-colors ${
                    minProficiency === lvl
                      ? "bg-brand-600 text-white"
                      : "bg-white dark:bg-slate-800 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-slate-700"
                  }`}
                >
                  {lvl}
                </button>
              ))}
            </div>
          </div>

          {/* Available only */}
          <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300 cursor-pointer select-none">
            <input
              type="checkbox"
              checked={availableOnly}
              onChange={(e) => setAvailableOnly(e.target.checked)}
              className="rounded border-gray-300 text-brand-600 focus:ring-brand-500"
            />
            Available in next 30 days
          </label>
        </div>

        {/* Results */}
        {debouncedSearch.trim().length > 0 && (
          <div className="border-t border-gray-100 dark:border-slate-700 pt-4">
            {isLoading ? (
              <div className="text-sm text-gray-400 animate-pulse">Searching...</div>
            ) : sorted.length === 0 ? (
              <p className="text-sm text-gray-400 dark:text-gray-500 italic">
                No resources found with &quot;{debouncedSearch}&quot; at proficiency {minProficiency}+.
              </p>
            ) : (
              <>
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                  {sorted.length} resource{sorted.length !== 1 ? "s" : ""} found
                </p>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50 dark:bg-slate-800 border-b border-gray-200 dark:border-slate-700">
                      <tr>
                        <SortableColumnHeader label="Resource" field="displayName" sortField={sortField} sortDir={sortDir} onSort={toggle} />
                        <SortableColumnHeader label="Chapter" field="chapter" sortField={sortField} sortDir={sortDir} onSort={toggle} />
                        <SortableColumnHeader label="Skill" field="skillName" sortField={sortField} sortDir={sortDir} onSort={toggle} />
                        <SortableColumnHeader label="Proficiency" field="skillProficiency" sortField={sortField} sortDir={sortDir} onSort={toggle} align="center" />
                        <SortableColumnHeader label="Utilization" field="utilizationPercent" sortField={sortField} sortDir={sortDir} onSort={toggle} align="right" />
                        <SortableColumnHeader label="Available From" field="availableFrom" sortField={sortField} sortDir={sortDir} onSort={toggle} />
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100 dark:divide-slate-700">
                      {sorted.map((r) => (
                        <tr key={r.id} className="hover:bg-gray-50 dark:hover:bg-slate-800/50">
                          <td className="px-4 py-2.5">
                            <Link href={`/resources/${r.id}`} className="font-medium text-gray-900 dark:text-gray-100 hover:text-brand-600 transition-colors">
                              {r.displayName}
                            </Link>
                          </td>
                          <td className="px-4 py-2.5 text-gray-500 dark:text-gray-400">{r.chapter ?? "---"}</td>
                          <td className="px-4 py-2.5 text-gray-700 dark:text-gray-300">{r.skillName}</td>
                          <td className="px-4 py-2.5 text-center"><ProficiencyBadge value={r.skillProficiency} /></td>
                          <td className="px-4 py-2.5 text-right">
                            <span className={`text-sm font-medium ${
                              r.utilizationPercent >= 90 ? "text-red-600 dark:text-red-400"
                                : r.utilizationPercent >= 70 ? "text-amber-600 dark:text-amber-400"
                                  : "text-green-600 dark:text-green-400"
                            }`}>
                              {r.utilizationPercent}%
                            </span>
                          </td>
                          <td className="px-4 py-2.5 text-gray-500 dark:text-gray-400 text-sm">{formatDate(r.availableFrom)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
