"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import Link from "next/link";
import { LineChart, Pencil, Search, Share2 } from "lucide-react";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { Badge } from "@/components/ui/Badge";
import { FilterBar, FilterPill } from "@/components/shared/FilterBar";
import { EmptyState } from "@/components/shared/EmptyState";
import { formatDate, formatNumber } from "@/lib/utils/format";
import type { ElectionListRow } from "@/lib/queries/election-queries";
import type { ElectionStatus } from "@/types";

interface ElectionsListProps {
  elections: ElectionListRow[];
}

const statusFilters: { label: string; value: ElectionStatus | "all" }[] = [
  { label: "All Elections", value: "all" },
  { label: "Open", value: "open" },
  { label: "Draft", value: "draft" },
  { label: "Closed", value: "closed" },
  { label: "Certified", value: "certified" },
];

export function ElectionsList({ elections }: ElectionsListProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const statusFilter =
    (searchParams.get("status") as ElectionStatus | "all") ?? "all";
  const search = searchParams.get("q") ?? "";
  const [searchInput, setSearchInput] = useState(search);

  useEffect(() => {
    setSearchInput(search);
  }, [search]);

  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchInput !== search) {
        setParams({ q: searchInput || null });
      }
    }, 300);
    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchInput]);

  function setParams(updates: Record<string, string | null>) {
    const params = new URLSearchParams(searchParams.toString());
    Object.entries(updates).forEach(([key, value]) => {
      if (value === null || value === "") params.delete(key);
      else params.set(key, value);
    });
    router.push(`/app/elections?${params.toString()}`);
  }

  const filtered = elections.filter((election) => {
    const matchesStatus =
      statusFilter === "all" || election.status === statusFilter;
    const matchesSearch =
      !search || election.title.toLowerCase().includes(search.toLowerCase());
    return matchesStatus && matchesSearch;
  });

  return (
    <>
      <FilterBar>
        <div className="flex flex-wrap gap-2">
          {statusFilters.map(({ label, value }) => (
            <FilterPill
              key={value}
              label={label}
              active={statusFilter === value}
              onClick={() => setParams({ status: value === "all" ? null : value })}
            />
          ))}
        </div>
        <div className="flex w-full items-center gap-2 rounded-sm border border-border bg-white px-3 py-2 text-muted sm:w-[260px]">
          <Search className="h-3.5 w-3.5 shrink-0" />
          <input
            type="search"
            placeholder="Search elections..."
            className="w-full border-none bg-transparent text-[13px] outline-none"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
          />
        </div>
      </FilterBar>

      <Card>
        {filtered.length === 0 ? (
          <EmptyState
            title={
              elections.length === 0
                ? "No elections yet"
                : "No elections match your filters"
            }
            description={
              elections.length === 0
                ? "Create your first election to start collecting ballots."
                : "Try adjusting your search or status filter."
            }
            action={
              elections.length === 0 ? (
                <Link href="/app/elections/new">
                  <Button>+ New Election</Button>
                </Link>
              ) : (
                <Button
                  variant="outline"
                  onClick={() => {
                    setSearchInput("");
                    setParams({ q: null, status: null });
                  }}
                >
                  Clear filters
                </Button>
              )
            }
          />
        ) : (
          <div className="-mx-4 overflow-x-auto sm:mx-0">
            <table className="w-full min-w-[640px] border-collapse text-[13px]">
              <thead>
                <tr>
                  {["Election", "Status", "Ballots", "Created", ""].map((label) => (
                    <th
                      key={label || "actions"}
                      className="border-b border-border bg-bg px-5 py-[11px] text-left text-[11.5px] font-bold uppercase tracking-wide text-muted"
                    >
                      {label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map((election) => (
                  <tr key={election.id} className="group hover:bg-[#FAFCFF]">
                    <td className="border-b border-border px-5 py-[13px] font-semibold">
                      <Link
                        href={`/app/elections/${election.id}`}
                        className="hover:text-primary"
                      >
                        {election.title}
                      </Link>
                      {election.isTestMode && (
                        <span className="ml-2 rounded-full bg-warning-bg px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-warning">
                          Test
                        </span>
                      )}
                    </td>
                    <td className="border-b border-border px-5 py-[13px]">
                      <Badge status={election.status} />
                    </td>
                    <td className="border-b border-border px-5 py-[13px] font-mono">
                      {formatNumber(election.voteCount)}
                    </td>
                    <td className="border-b border-border px-5 py-[13px] text-muted">
                      {formatDate(election.createdAt)}
                    </td>
                    <td className="border-b border-border px-5 py-[13px]">
                      <div className="flex gap-1.5">
                        <Link
                          href={
                            election.status === "certified"
                              ? `/app/elections/${election.id}`
                              : `/app/elections/${election.id}/edit`
                          }
                          title={
                            election.status === "certified"
                              ? "Open"
                              : "Edit election"
                          }
                        >
                          <Button variant="icon" size="row" type="button">
                            <Pencil className="h-3.5 w-3.5" />
                          </Button>
                        </Link>
                        <Link
                          href={`/app/elections/${election.id}?tab=distribute`}
                          title="Share"
                        >
                          <Button variant="icon" size="row" type="button">
                            <Share2 className="h-3.5 w-3.5" />
                          </Button>
                        </Link>
                        <Link
                          href={`/app/elections/${election.id}?tab=results`}
                          title="Results"
                        >
                          <Button variant="icon" size="row" type="button">
                            <LineChart className="h-3.5 w-3.5" />
                          </Button>
                        </Link>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </>
  );
}

export function NewElectionButton() {
  const [isPending, startTransition] = useTransition();
  const router = useRouter();

  return (
    <Button
      size="sm"
      loading={isPending}
      onClick={() => startTransition(() => router.push("/app/elections/new"))}
    >
      + New Election
    </Button>
  );
}
