"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useTransition, useState, useEffect } from "react";
import Link from "next/link";
import {
  Pencil,
  Share2,
  LineChart,
  Copy,
  Trash2,
  Search,
} from "lucide-react";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { FilterBar, FilterPill } from "@/components/shared/FilterBar";
import { EmptyState } from "@/components/shared/EmptyState";
import { SurveyStatusSelect } from "@/components/features/surveys/SurveyStatusSelect";
import { formatDate, formatNumber } from "@/lib/utils/format";
import { swalConfirm } from "@/lib/utils/swal";
import {
  duplicateSurvey,
  deleteSurvey,
  createSurvey,
} from "@/lib/actions/surveys";
import type { SurveyStatus } from "@/types";
import { cn } from "@/lib/utils/cn";

export interface SurveyRow {
  id: string;
  title: string;
  status: SurveyStatus;
  responseCount: number;
  createdAt: Date | string;
}

interface SurveyTableProps {
  surveys: SurveyRow[];
}

const statusFilters: { label: string; value: SurveyStatus | "all" }[] = [
  { label: "All Surveys", value: "all" },
  { label: "Active", value: "active" },
  { label: "Draft", value: "draft" },
  { label: "Closed", value: "closed" },
];

export function SurveyTable({ surveys }: SurveyTableProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  const statusFilter =
    (searchParams.get("status") as SurveyStatus | "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/surveys?${params.toString()}`);
  }

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

  async function handleDuplicate(id: string) {
    startTransition(async () => {
      await duplicateSurvey(id);
      router.refresh();
    });
  }

  async function handleDelete(id: string, title: string) {
    const ok = await swalConfirm({
      title: `Delete "${title}"?`,
      text: "This action cannot be undone. All responses will be permanently deleted.",
      confirmText: "Delete",
      cancelText: "Cancel",
      danger: true,
    });
    if (!ok) return;
    startTransition(async () => {
      await deleteSurvey(id);
      router.refresh();
    });
  }

  async function handleCreate() {
    startTransition(async () => {
      const result = await createSurvey();
      if (result.success && result.data) {
        router.push(`/app/surveys/${result.data.surveyId}/build`);
      }
    });
  }

  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 surveys..."
            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={
              surveys.length === 0
                ? "No surveys yet"
                : "No surveys match your filters"
            }
            description={
              surveys.length === 0
                ? "Create your first survey to start collecting responses."
                : "Try adjusting your search or status filter."
            }
              action={
              surveys.length === 0 ? (
                <Button onClick={handleCreate} loading={isPending}>
                  {isPending ? "Creating…" : "+ New Survey"}
                </Button>
              ) : (
                <Button
                  variant="outline"
                  onClick={() => {
                    setSearchInput("");
                    setParams({ q: null, status: null });
                  }}
                >
                  Clear filters
                </Button>
              )
            }
          />
        ) : (
          <div className="overflow-x-auto -mx-4 sm:mx-0">
          <table className="w-full min-w-[640px] border-collapse text-[13px]">
              <thead>
                <tr>
                  <th className="border-b border-border bg-bg px-5 py-[11px] text-left text-[11.5px] font-bold uppercase tracking-wide text-muted">
                    Survey
                  </th>
                  <th className="border-b border-border bg-bg px-5 py-[11px] text-left text-[11.5px] font-bold uppercase tracking-wide text-muted">
                    Status
                  </th>
                  <th className="border-b border-border bg-bg px-5 py-[11px] text-left text-[11.5px] font-bold uppercase tracking-wide text-muted">
                    Responses
                  </th>
                  <th className="border-b border-border bg-bg px-5 py-[11px] text-left text-[11.5px] font-bold uppercase tracking-wide text-muted">
                    Created
                  </th>
                  <th className="border-b border-border bg-bg px-5 py-[11px]" />
                </tr>
              </thead>
              <tbody>
                {filtered.map((survey) => (
                  <tr
                    key={survey.id}
                    className="group hover:bg-[#FAFCFF]"
                  >
                    <td className="border-b border-border px-5 py-[13px] font-semibold">
                      <Link
                        href={`/app/surveys/${survey.id}/build`}
                        className="hover:text-primary"
                      >
                        {survey.title}
                      </Link>
                    </td>
                    <td className="border-b border-border px-5 py-[13px]">
                      <SurveyStatusSelect
                        surveyId={survey.id}
                        status={survey.status}
                      />
                    </td>
                    <td className="border-b border-border px-5 py-[13px] font-mono">
                      {formatNumber(survey.responseCount)}
                    </td>
                    <td className="border-b border-border px-5 py-[13px] text-muted">
                      {formatDate(survey.createdAt)}
                    </td>
                    <td className="border-b border-border px-5 py-[13px]">
                      <div className="flex gap-1.5">
                        <Link
                          href={`/app/surveys/${survey.id}/build`}
                          title="Edit"
                        >
                          <Button variant="icon" size="row" type="button">
                            <Pencil className="h-3.5 w-3.5" />
                          </Button>
                        </Link>
                        <Link
                          href={`/app/surveys/${survey.id}/distribute`}
                          title="Share"
                        >
                          <Button variant="icon" size="row" type="button">
                            <Share2 className="h-3.5 w-3.5" />
                          </Button>
                        </Link>
                        <Link
                          href={`/app/surveys/${survey.id}/results`}
                          title="Results"
                        >
                          <Button variant="icon" size="row" type="button">
                            <LineChart className="h-3.5 w-3.5" />
                          </Button>
                        </Link>
                        <Button
                          variant="icon"
                          size="row"
                          type="button"
                          title="Duplicate"
                          disabled={isPending}
                          onClick={() => handleDuplicate(survey.id)}
                        >
                          <Copy className="h-3.5 w-3.5" />
                        </Button>
                        <Button
                          variant="icon"
                          size="row"
                          type="button"
                          title="Delete"
                          disabled={isPending}
                          className={cn("hover:text-danger")}
                          onClick={() =>
                            handleDelete(survey.id, survey.title)
                          }
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </>
  );
}

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

  function handleCreate() {
    startTransition(async () => {
      const result = await createSurvey();
      if (result.success && result.data) {
        router.push(`/app/surveys/${result.data.surveyId}/build`);
      }
    });
  }

  return (
    <Button size="sm" onClick={handleCreate} loading={isPending}>
      {isPending ? "Creating…" : "+ New Survey"}
    </Button>
  );
}
