import { useState, useMemo } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { AlertTriangle, List, LayoutGrid, Plus, Search } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { issueList } from '@/client';
import { useProject } from '@/contexts';
import { normalizeIssueList } from './issues/config';
import type { IssueResponse } from '@/client';
import type { ViewMode } from './issues/config';
import { BoardColumn } from './issues/board-column';
import { ListRow } from './issues/list-row';
import { ALL_STATUSES } from './issues/config';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';

export function ProjectIssues() {
    const { project } = useProject();
    const navigate = useNavigate();

    const [search, setSearch] = useState('');
    const [viewMode, setViewMode] = useState<ViewMode>('board');

    const { data: issuesRaw, isLoading, isError, error } = useQuery({
        queryKey: ['projectIssues', project?.name],
        queryFn: async () => {
            const resp = await issueList({
                path: { project: project!.name },
                query: { page: 1, per_page: 100 },
            });
            return resp.data?.data ?? null;
        },
        enabled: !!project?.name,
    });

    const { items: allIssues, total } = normalizeIssueList(issuesRaw);

    const filtered = useMemo(() => {
        if (!search.trim()) return allIssues;
        const q = search.toLowerCase();
        return allIssues.filter(
            (i) =>
                i.title.toLowerCase().includes(q) ||
                (i.body ?? '').toLowerCase().includes(q) ||
                String(i.number).includes(q),
        );
    }, [allIssues, search]);

    const issuesByStatus = useMemo(() => {
        const map = new Map<string, IssueResponse[]>();
        for (const s of ALL_STATUSES) map.set(s, []);
        for (const issue of filtered) {
            const list = map.get(issue.state);
            if (list) list.push(issue);
        }
        return map;
    }, [filtered]);

    const openCount = issuesByStatus.get('open')?.length ?? 0;
    const closedCount = issuesByStatus.get('closed')?.length ?? 0;

    if (!project) return null;

    return (
        <div className="flex-1 overflow-auto flex flex-col">
            {/* ── Header bar ── */}
            <div className="border-b shrink-0">
                <div className="flex items-center justify-between px-6 py-3">
                    {/* Breadcrumb */}
                    <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
                        <Link to="/" className="hover:text-foreground transition-colors">Projects</Link>
                        <span>/</span>
                        <Link to={`/project/${project.name}`} className="hover:text-foreground font-medium transition-colors">
                            {project.name}
                        </Link>
                        <span>/</span>
                        <span className="text-foreground">Issues</span>
                    </div>

                    {/* Controls */}
                    <div className="flex items-center gap-2">
                        {/* Search */}
                        <div className="relative">
                            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
                            <input
                                type="text"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder="Search issues…"
                                className="h-8 pl-8 pr-3 text-sm border rounded-md w-44 bg-background focus:outline-none focus:ring-2 focus:ring-ring"
                            />
                        </div>

                        {/* View toggle */}
                        <div className="flex items-center border rounded-md overflow-hidden">
                            <button
                                className={`flex items-center gap-1.5 px-2.5 h-8 text-sm transition-colors ${
                                    viewMode === 'board'
                                        ? 'bg-primary text-primary-foreground'
                                        : 'text-muted-foreground hover:bg-muted'
                                }`}
                                onClick={() => setViewMode('board')}
                                title="Board view"
                            >
                                <LayoutGrid className="h-3.5 w-3.5" />
                                <span className="hidden sm:inline">Board</span>
                            </button>
                            <button
                                className={`flex items-center gap-1.5 px-2.5 h-8 text-sm transition-colors ${
                                    viewMode === 'list'
                                        ? 'bg-primary text-primary-foreground'
                                        : 'text-muted-foreground hover:bg-muted'
                                }`}
                                onClick={() => setViewMode('list')}
                                title="List view"
                            >
                                <List className="h-3.5 w-3.5" />
                                <span className="hidden sm:inline">List</span>
                            </button>
                        </div>

                        <Button
                            size="sm"
                            onClick={() => navigate(`/project/${project.name}/issues/new`)}
                        >
                            <Plus className="mr-1.5 h-3.5 w-3.5" />
                            New
                        </Button>
                    </div>
                </div>
            </div>

            {/* ── Stats row ── */}
            <div className="border-b px-6 py-2.5 shrink-0">
                <div className="flex items-center gap-5 text-sm">
                    <div className="flex items-center gap-1.5 text-muted-foreground">
                        <span className="h-2 w-2 rounded-full bg-emerald-500" />
                        {openCount} Open
                    </div>
                    <div className="flex items-center gap-1.5 text-muted-foreground">
                        <span className="h-2 w-2 rounded-full bg-violet-500" />
                        {closedCount} Closed
                    </div>
                    {search && (
                        <span className="text-xs text-muted-foreground">
                            {filtered.length} of {total} shown
                        </span>
                    )}
                </div>
            </div>

            {/* ── Content ── */}
            {isLoading ? (
                <div className="flex items-center justify-center flex-1">
                    <Spinner />
                </div>
            ) : isError ? (
                <div className="p-6">
                    <div className="rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive text-sm flex items-center gap-2">
                        <AlertTriangle className="h-4 w-4 flex-shrink-0" />
                        <strong>Error:</strong>{' '}
                        {error instanceof Error ? error.message : 'Failed to load issues'}
                    </div>
                </div>
            ) : filtered.length === 0 ? (
                <div className="flex flex-col items-center justify-center flex-1 py-20 text-center">
                    <svg
                        className="mb-4 h-10 w-10 text-muted-foreground/40"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                    >
                        <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={1.5}
                            d="M9 12h6m-6 4h6m2 5H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5.586a1 1 0 0 1 .707.293l5.414 5.414a1 1 0 0 1 .293.707V19a2 2 0 0 1-2 2z"
                        />
                    </svg>
                    <p className="text-sm font-medium text-muted-foreground">No issues found</p>
                    {search && (
                        <button
                            onClick={() => setSearch('')}
                            className="mt-2 text-xs text-primary hover:underline"
                        >
                            Clear search
                        </button>
                    )}
                </div>
            ) : viewMode === 'board' ? (
                /* ── Board view ── */
                <div className="flex flex-1 gap-4 overflow-x-auto p-4">
                    {ALL_STATUSES.map((status) => (
                        <BoardColumn
                            key={status}
                            status={status}
                            issues={issuesByStatus.get(status) ?? []}
                            onCardClick={(issue) =>
                                navigate(`/project/${project.name}/issues/${issue.number}`)
                            }
                            onAddIssue={() =>
                                navigate(`/project/${project.name}/issues/new`)
                            }
                        />
                    ))}
                </div>
            ) : (
                /* ── List view ── */
                <div className="flex-1 overflow-y-auto">
                    <div className="border-b bg-muted/30">
                        <div className="flex h-9 items-center gap-3 px-4 text-xs font-medium text-muted-foreground">
                            <div className="w-4 shrink-0" />
                            <div className="w-12 shrink-0">#</div>
                            <div className="flex-1">Title</div>
                            <div className="shrink-0 hidden md:inline">Author</div>
                            <div className="shrink-0 hidden sm:inline">Date</div>
                        </div>
                    </div>
                    <div className="divide-y divide-border">
                        {filtered.map((issue) => (
                            <ListRow
                                key={issue.number}
                                issue={issue}
                                onClick={() =>
                                    navigate(`/project/${project.name}/issues/${issue.number}`)
                                }
                            />
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
}
