"use client";

import { useMemo, useState } from "react";
import EmptyState from "@/components/EmptyState";
import SchemaCheckModal from "@/components/SchemaCheckModal";
import SubgraphBadge from "@/components/SubgraphBadge";
import { useApp } from "@/context/AppContext";
import {
    buildGithubSearchUrl,
    buildGithubOrgSearchUrl,
    type DeadItem,
    getFilteredItems,
    PAGE_SIZE,
} from "@/lib/utils";
import type { DeadObject, DeadObjectField, TabKey } from "@/lib/types";
import  { ExternalLinkIcon } from "@/components/externalLinkIcon";

interface CheckTarget {
    subgraph: string;
    parentType: string;
    fieldName: string | null;
}

const COLUMNS: Record<TabKey, string[]> = {
    queries: ["Field", "Subgraph", "Studio", "GitHub", "Check"],
    mutations: ["Field", "Subgraph", "Studio", "GitHub", "Check"],
    object_fields: ["Type", "Field", "Subgraph", "Studio", "GitHub", "Check"],
    objects: ["Object", "Fields", "Subgraph", "Studio", "GitHub", "Check"],
};

function PaginationBar({
    page,
    totalPages,
    totalItems,
    onPageChange,
}: {
    page: number;
    totalPages: number;
    totalItems: number;
    onPageChange: (p: number) => void;
}) {
    const start = (page - 1) * PAGE_SIZE + 1;
    const end = Math.min(page * PAGE_SIZE, totalItems);

    const pageNumbers = useMemo(() => {
        const pages: (number | "ellipsis-start" | "ellipsis-end")[] = [];
        if (totalPages <= 7) {
            for (let i = 1; i <= totalPages; i++) pages.push(i);
            return pages;
        }

        pages.push(1);

        if (page > 3) {
            pages.push("ellipsis-start");
        }

        for (
            let i = Math.max(2, page - 1);
            i <= Math.min(totalPages - 1, page + 1);
            i++
        ) {
            pages.push(i);
        }

        if (page < totalPages - 2) {
            pages.push("ellipsis-end");
        }

        pages.push(totalPages);

        return pages;
    }, [page, totalPages]);

    return (
        <div className="flex items-center justify-between px-4 py-3 border-t border-border">
            <span className="text-sm text-text-secondary">
                Showing {start}&ndash;{end} of {totalItems}
            </span>
            <div className="flex items-center gap-1">
                <button
                    onClick={() => onPageChange(page - 1)}
                    disabled={page <= 1}
                    className="px-3 py-1.5 rounded-md text-sm bg-raised border border-border text-text-secondary hover:text-text-primary hover:bg-raised disabled:opacity-40 cursor-pointer disabled:cursor-default transition-colors"
                >
                    Previous
                </button>
                {pageNumbers.map(p => {
                    if (typeof p === "string") {
                        return (
                            <span
                                key={p}
                                className="px-2 py-1.5 text-sm text-text-secondary"
                            >
                                &hellip;
                            </span>
                        );
                    }
                    const isActive = p === page;
                    return (
                        <button
                            key={p}
                            onClick={() => onPageChange(p)}
                            className={`px-3 py-1.5 rounded-md text-sm border cursor-pointer transition-colors ${
                                isActive
                                    ? "bg-accent text-white border-accent"
                                    : "bg-raised border-border text-text-secondary hover:text-text-primary hover:bg-raised"
                            }`}
                        >
                            {p}
                        </button>
                    );
                })}
                <button
                    onClick={() => onPageChange(page + 1)}
                    disabled={page >= totalPages}
                    className="px-3 py-1.5 rounded-md text-sm bg-raised border border-border text-text-secondary hover:text-text-primary hover:bg-raised disabled:opacity-40 cursor-pointer disabled:cursor-default transition-colors"
                >
                    Next
                </button>
            </div>
        </div>
    );
}

export default function DataTable() {
    const { data, activeTab, search, selectedSubgraph, page, setPage } =
        useApp();
    const [checkTarget, setCheckTarget] = useState<CheckTarget | null>(null);

    const filtered = useMemo(() => {
        if (!data) return [];
        return getFilteredItems(data, activeTab, search, selectedSubgraph);
    }, [data, activeTab, search, selectedSubgraph]);

    const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
    const pageItems = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
    const columns = COLUMNS[activeTab];

    if (!data) return null;

    if (filtered.length === 0) {
        return (
            <div className="px-6 py-4">
                <EmptyState />
            </div>
        );
    }

    return (
        <div className="px-6 py-4">
            <div className="bg-surface border border-border rounded-lg overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full">
                        <thead>
                            <tr className="text-left text-xs uppercase tracking-wider text-text-secondary border-b border-border">
                                {columns.map(col => (
                                    <th
                                        key={col}
                                        className="px-4 py-3 font-medium"
                                    >
                                        {col}
                                    </th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {pageItems.map((item, index) => (
                                <Row
                                    key={index}
                                    item={item}
                                    tabKey={activeTab}
                                    onCheck={setCheckTarget}
                                />
                            ))}
                        </tbody>
                    </table>
                </div>
                {totalPages > 1 && (
                    <PaginationBar
                        page={page}
                        totalPages={totalPages}
                        totalItems={filtered.length}
                        onPageChange={setPage}
                    />
                )}
            </div>
            {checkTarget && (
                <SchemaCheckModal
                    target={checkTarget}
                    onClose={() => setCheckTarget(null)}
                />
            )}
        </div>
    );
}

function CheckIcon() {
    return (
        <svg
            className="w-4 h-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
        >
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"
            />
        </svg>
    );
}

function Row({
    item,
    tabKey,
    onCheck,
}: {
    item: DeadItem;
    tabKey: TabKey;
    onCheck: (target: CheckTarget) => void;
}) {
    const studioUrl =
        "studio_url" in item ? (item as { studio_url: string }).studio_url : "";
    const githubUrl = buildGithubSearchUrl(item, tabKey);

    if (tabKey === "object_fields") {
        const obj = item as unknown as DeadObjectField;
        return (
            <tr className="border-b border-border/50 hover:bg-raised/50 transition-colors">
                <td className="px-4 py-3 text-sm font-mono text-accent">
                    {obj.type}
                </td>
                <td className="px-4 py-3 text-sm font-mono text-text-primary">
                    {obj.field}
                </td>
                <td className="px-4 py-3 text-sm">
                    <SubgraphBadge subgraph={obj.subgraph} />
                </td>
                <td className="px-4 py-3 text-sm">
                    <a
                        href={studioUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-text-secondary hover:text-accent transition-colors"
                    >
                        <ExternalLinkIcon />
                    </a>
                </td>
                <td className="px-4 py-3 text-sm">
                    <a
                        href={githubUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-text-secondary hover:text-accent transition-colors"
                    >
                        <ExternalLinkIcon />
                    </a>
                </td>
                <td className="px-4 py-3 text-sm">
                    <button
                        onClick={() =>
                            onCheck({
                                subgraph: obj.subgraph,
                                parentType: obj.type,
                                fieldName: obj.field,
                            })
                        }
                        className="text-text-secondary hover:text-accent transition-colors cursor-pointer"
                        title={`Check removal of ${obj.type}.${obj.field}`}
                    >
                        <CheckIcon />
                    </button>
                </td>
            </tr>
        );
    }

    if (tabKey === "objects") {
        const obj = item as unknown as DeadObject;
        const githubOrgUrl = buildGithubOrgSearchUrl(item, tabKey);
        return (
            <tr className="border-b border-border/50 hover:bg-raised/50 transition-colors">
                <td className="px-4 py-3 text-sm font-mono text-text-primary">
                    {obj.object}
                </td>
                <td className="px-4 py-3 text-sm text-text-secondary">
                    {obj.field_count}
                </td>
                <td className="px-4 py-3 text-sm">
                    <SubgraphBadge subgraph={obj.subgraph} />
                </td>
                <td className="px-4 py-3 text-sm">
                    <a
                        href={studioUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-text-secondary hover:text-accent transition-colors"
                    >
                        <ExternalLinkIcon />
                    </a>
                </td>
                <td className="px-4 py-3 text-sm">
                    <div className="flex items-center gap-2">
                        <a
                            href={githubOrgUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-text-secondary hover:text-accent transition-colors text-xs"
                            title="Search across org"
                        >
                            org
                        </a>
                        <a
                            href={githubUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-text-secondary hover:text-accent transition-colors text-xs"
                            title="Find definition in repo"
                        >
                            def
                        </a>
                    </div>
                </td>
                <td className="px-4 py-3 text-sm">
                    <button
                        onClick={() =>
                            onCheck({
                                subgraph: obj.subgraph,
                                parentType: obj.object,
                                fieldName: null,
                            })
                        }
                        className="text-text-secondary hover:text-accent transition-colors cursor-pointer"
                        title={`Check removal of ${obj.object}`}
                    >
                        <CheckIcon />
                    </button>
                </td>
            </tr>
        );
    }

    // queries and mutations share the same shape
    const typedItem = item as {
        field: string;
        subgraph: string;
        studio_url: string;
    };
    const field = typedItem.field;
    const subgraph = typedItem.subgraph;
    const parentType = tabKey === "queries" ? "Query" : "Mutation";
    const githubOrgUrl = buildGithubOrgSearchUrl(item, tabKey);

    return (
        <tr className="border-b border-border/50 hover:bg-raised/50 transition-colors">
            <td className="px-4 py-3 text-sm font-mono text-text-primary">
                {field}
            </td>
            <td className="px-4 py-3 text-sm">
                <SubgraphBadge subgraph={subgraph} />
            </td>
            <td className="px-4 py-3 text-sm">
                <a
                    href={studioUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-text-secondary hover:text-accent transition-colors"
                >
                    <ExternalLinkIcon />
                </a>
            </td>
            <td className="px-4 py-3 text-sm">
                <div className="flex items-center gap-2">
                    <a
                        href={githubOrgUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-text-secondary hover:text-accent transition-colors text-xs"
                        title="Search across org"
                    >
                        org
                    </a>
                    <a
                        href={githubUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-text-secondary hover:text-accent transition-colors text-xs"
                        title="Find definition in repo"
                    >
                        def
                    </a>
                </div>
            </td>
            <td className="px-4 py-3 text-sm">
                <button
                    onClick={() =>
                        onCheck({
                            subgraph,
                            parentType,
                            fieldName: field,
                        })
                    }
                    className="text-text-secondary hover:text-accent transition-colors cursor-pointer"
                    title={`Check removal of ${parentType}.${field}`}
                >
                    <CheckIcon />
                </button>
            </td>
        </tr>
    );
}
