import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import {
    AlertTriangle,
    Copy,
    FileText,
    GitCommit,
    HardDrive,
    Loader2,
    Plus,
    RefreshCw,
    Search,
    Trash2,
    X,
} from 'lucide-react';
import {
    skillDelete,
    skillList,
    skillScan,
    type SkillResponse,
} from '@/client';
import { useProject } from '@/contexts';

type SourceFilter = 'all' | 'manual' | 'repo';

// ─── Helpers ─────────────────────────────────────────────────────────────────

function sourceIcon(source: string) {
    return source === 'repo' ? (
        <GitCommit className="h-3 w-3" />
    ) : (
        <HardDrive className="h-3 w-3" />
    );
}

// ─── Delete Confirm ──────────────────────────────────────────────────────────

function DeleteConfirm({
    name,
    loading,
    onClose,
    onConfirm,
}: {
    name: string;
    loading: boolean;
    onClose: () => void;
    onConfirm: () => void;
}) {
    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
            <div
                className="absolute inset-0 bg-black/70 backdrop-blur-sm"
                onClick={onClose}
            />
            <div className="relative bg-white border border-[#D4D4D8] rounded-xl w-full max-w-sm p-5 shadow-2xl">
                <div className="flex items-center justify-between mb-4">
                    <h2 className="text-[13px] font-semibold flex items-center gap-2 text-[#18181B]">
                        <AlertTriangle className="w-4 h-4 text-amber-400" />
                        Delete skill
                    </h2>
                    <button
                        onClick={onClose}
                        className="text-[#71717A] hover:text-[#27272A] p-1 rounded transition-colors bg-transparent border-0 cursor-pointer"
                    >
                        <X className="w-4 h-4" />
                    </button>
                </div>
                <p className="text-[13px] text-[#52525B] mb-5">
                    Are you sure you want to delete &ldquo;{name}&rdquo;? This cannot be undone.
                </p>
                <div className="flex justify-end gap-2">
                    <button
                        onClick={onClose}
                        className="px-3 py-1.5 rounded-[4px] text-[13px] font-medium text-[#52525B] hover:text-[#27272A] hover:bg-[#F4F4F5] transition-colors bg-transparent border-0 cursor-pointer"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={onConfirm}
                        disabled={loading}
                        className="px-3 py-1.5 rounded-[4px] bg-[#DC2626]/90 hover:bg-[#EF4444] text-white text-[13px] font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed border border-[#DC2626]/50 cursor-pointer"
                    >
                        {loading ? (
                            <Loader2 className="h-4 w-4 animate-spin mx-auto" />
                        ) : (
                            'Delete'
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
}

// ─── Skill Card ───────────────────────────────────────────────────────────────

function SkillCard({
    skill,
    onDelete,
}: {
    skill: SkillResponse;
    onDelete: () => void;
}) {
    const isRepo = skill.source === 'repo';
    const [copied, setCopied] = useState(false);
    const contentLines = (skill.content ?? '')
        .split('\n')
        .filter(Boolean)
        .slice(0, 4);
    const totalLines = (skill.content ?? '').split('\n').filter(Boolean).length;

    const handleCopy = () => {
        navigator.clipboard.writeText(skill.content ?? '').then(() => {
            setCopied(true);
            setTimeout(() => setCopied(false), 1500);
        });
    };

    return (
        <div
            className={cn(
                'group relative rounded-xl border border-[#E4E4E7] bg-white',
                'flex flex-col overflow-hidden',
                'transition-all hover:border-[#D4D4D8] hover:bg-[#F4F4F5]/40 hover:shadow-sm',
            )}
        >
            {/* Top-right hover actions */}
            <div
                className={cn(
                    'absolute right-2 top-2 flex items-center gap-0.5',
                    'rounded-lg border border-[#E4E4E7] bg-white px-1 py-0.5 shadow-sm',
                    'opacity-0 group-hover:opacity-100 transition-opacity z-10',
                )}
            >
                <button
                    onClick={handleCopy}
                    title="Copy content"
                    className="rounded p-1 text-[#71717A] hover:text-[#27272A] hover:bg-[#F4F4F5] transition-colors bg-transparent border-0 cursor-pointer"
                >
                    {copied ? (
                        <span className="text-[11px] text-[#18181B] font-medium">Copied</span>
                    ) : (
                        <Copy className="h-3.5 w-3.5" />
                    )}
                </button>
                <button
                    onClick={onDelete}
                    title="Delete"
                    className="rounded p-1 text-[#8B8B94] hover:text-[#DC2626] transition-colors bg-transparent border-0 cursor-pointer"
                >
                    <Trash2 className="h-3.5 w-3.5" />
                </button>
            </div>

            {/* Card body */}
            <div className="flex flex-col gap-2.5 px-4 pt-4 pb-1">
                {/* Name row */}
                <div className="flex items-center gap-2 pr-16">
                    <h3 className="flex-1 truncate text-[14px] font-semibold text-[#18181B]">
                        {skill.name || skill.slug}
                    </h3>
                </div>

                {/* Slug + source */}
                <div className="flex items-center gap-1.5 flex-wrap">
                    <code className="text-[12px] px-2 py-0.5 rounded-md bg-[#F4F4F5] font-mono text-[#71717A]">
                        {skill.slug}
                    </code>
                    <span
                        className={cn(
                            'inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-[12px] font-medium',
                            isRepo
                                ? 'border-[#18181B]/20 bg-[#18181B]/5 text-[#18181B]'
                                : 'border-[#E4E4E7] bg-[#F4F4F5] text-[#52525B]',
                        )}
                    >
                        {sourceIcon(skill.source)}
                        {isRepo ? 'repo' : 'manual'}
                    </span>
                    {isRepo && skill.commit_sha && (
                        <span className="inline-flex items-center gap-1 text-[12px] text-[#8B8B94] font-mono">
                            <GitCommit className="h-3 w-3" />
                            {skill.commit_sha.slice(0, 7)}
                        </span>
                    )}
                </div>

                {/* Description */}
                {skill.description && (
                    <p className="text-[13px] leading-[18px] text-[#52525B] line-clamp-2">
                        {skill.description}
                    </p>
                )}
            </div>

            {/* Content preview */}
            {contentLines.length > 0 && (
                <div className="mx-4 mb-3 rounded-lg bg-[#F4F4F5] border border-[#E4E4E7] p-3">
                    <div className="flex items-center gap-1.5 mb-2">
                        <FileText className="h-3 w-3 text-[#8B8B94]" />
                        <span className="text-[10px] font-semibold uppercase tracking-[0.08em] text-[#8B8B94]">
                            Content
                        </span>
                    </div>
                    <pre className="text-[12px] font-mono leading-5 text-[#52525B] whitespace-pre-wrap break-all">
                        {contentLines.join('\n')}
                    </pre>
                    {totalLines > 4 && (
                        <p className="mt-2 text-[11px] text-[#8B8B94] italic">
                            +{totalLines - 4} more lines
                        </p>
                    )}
                </div>
            )}

            {/* Card footer */}
            <div className="mt-auto flex items-center justify-between gap-2 border-t border-[#E4E4E7] px-4 py-2.5">
                <span className="text-[12px] text-[#8B8B94]">
                    {isRepo ? 'Scanned from repository' : 'Added manually'}
                </span>
                {skill.blob_hash && (
                    <span className="text-[11px] font-mono text-[#8B8B94]">
                        {skill.blob_hash.slice(0, 7)}
                    </span>
                )}
            </div>
        </div>
    );
}

// ─── Skeleton Card ───────────────────────────────────────────────────────────

function SkeletonCard() {
    return (
        <div className="rounded-xl border border-[#E4E4E7] bg-white overflow-hidden">
            <div className="px-4 pt-4 pb-3 space-y-2">
                <div className="h-4 w-2/3 rounded bg-[#F4F4F5] animate-pulse" />
                <div className="flex gap-1.5">
                    <div className="h-4 w-20 rounded-md bg-[#F4F4F5] animate-pulse" />
                    <div className="h-4 w-14 rounded-full bg-[#F4F4F5] animate-pulse" />
                </div>
                <div className="h-3 w-full rounded bg-[#F4F4F5] animate-pulse" />
            </div>
            <div className="mx-4 mb-3 rounded-lg bg-[#F4F4F5] border border-[#E4E4E7] p-3 space-y-1.5">
                <div className="h-3 w-full rounded bg-[#E4E4E7] animate-pulse" />
                <div className="h-3 w-4/5 rounded bg-[#E4E4E7] animate-pulse" />
                <div className="h-3 w-3/5 rounded bg-[#E4E4E7] animate-pulse" />
            </div>
            <div className="border-t border-[#E4E4E7] px-4 py-2.5">
                <div className="h-3 w-24 rounded bg-[#F4F4F5] animate-pulse" />
            </div>
        </div>
    );
}

// ─── Main Page ───────────────────────────────────────────────────────────────

export function SettingsSkills() {
    const { project } = useProject();
    const navigate = useNavigate();
    const [skills, setSkills] = useState<SkillResponse[]>([]);
    const [loading, setLoading] = useState(true);
    const [filter, setFilter] = useState<SourceFilter>('all');
    const [search, setSearch] = useState('');
    const [scanLoading, setScanLoading] = useState(false);
    const [deleteTarget, setDeleteTarget] = useState<SkillResponse | null>(null);
    const [deleteLoading, setDeleteLoading] = useState(false);

    useEffect(() => {
        if (!project?.name) return;
        setLoading(true);
        skillList({ path: { project_name: project.name }, params: {} })
            .then((resp) => setSkills(resp.data?.data ?? []))
            .catch(() => toast.error('Failed to load skills'))
            .finally(() => setLoading(false));
    }, [project?.name]);

    const filtered = skills.filter((s) => {
        const matchesFilter = filter === 'all' || s.source === filter;
        const matchesSearch =
            !search ||
            s.name?.toLowerCase().includes(search.toLowerCase()) ||
            s.slug.toLowerCase().includes(search.toLowerCase()) ||
            (s.description ?? '').toLowerCase().includes(search.toLowerCase());
        return matchesFilter && matchesSearch;
    });

    const manualCount = skills.filter((s) => s.source === 'manual').length;
    const repoCount = skills.filter((s) => s.source === 'repo').length;

    const handleScan = async () => {
        if (!project?.name) return;
        setScanLoading(true);
        try {
            await skillScan({ path: { project_name: project.name } });
            toast.success('Repositories scanned successfully');
            const resp = await skillList({
                path: { project_name: project.name },
                params: {},
            });
            setSkills(resp.data?.data ?? []);
        } catch {
            toast.error('Failed to scan repositories');
        } finally {
            setScanLoading(false);
        }
    };

    const handleDelete = async () => {
        if (!project?.name || !deleteTarget) return;
        setDeleteLoading(true);
        try {
            await skillDelete({
                path: { project_name: project.name, slug: deleteTarget.slug },
            });
            toast.success(`"${deleteTarget.name}" deleted`);
            setDeleteTarget(null);
            const resp = await skillList({
                path: { project_name: project.name },
                params: {},
            });
            setSkills(resp.data?.data ?? []);
        } catch {
            toast.error('Failed to delete skill');
        } finally {
            setDeleteLoading(false);
        }
    };

    return (
        <div className="mx-auto flex min-h-full w-full max-w-[1200px] flex-col gap-6 px-6 pt-6 pb-8">
            {/* Page Header */}
            <div className="border-b border-[#E4E4E7] pb-4">
                <div className="flex items-center gap-3">
                    <h1 className="text-[17px] font-semibold tracking-tight flex items-center gap-2">
                        Skills
                        <span className="inline-flex items-center rounded-full border border-[#E4E4E7] bg-[#F4F4F5] px-2.5 py-0.5 text-[12px] font-medium text-[#52525B]">
                            {skills.length}
                        </span>
                    </h1>
                    <span className="text-[13px] text-[#71717A]">
                        Agent instructions for this project
                    </span>
                </div>
            </div>

            {/* Toolbar */}
            <div className="flex flex-wrap items-center justify-between gap-3">
                {/* Left: search + filters */}
                <div className="flex items-center gap-3 flex-wrap">
                    {/* Search */}
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[#71717A]" />
                        <input
                            type="text"
                            value={search}
                            onChange={(e) => setSearch(e.target.value)}
                            placeholder="Search skills..."
                            className={cn(
                                'h-10 rounded-lg border border-[#E4E4E7] bg-white px-3 pl-9 text-[13px] text-[#27272A]',
                                'placeholder:text-[#8B8B94] outline-none transition-colors',
                                'focus:border-[#D4D4D8]',
                            )}
                            style={{ width: 220 }}
                        />
                    </div>

                    {/* Segmented filter */}
                    <div className="flex rounded-lg border border-[#E4E4E7] bg-white p-0.5">
                        {(
                            [
                                { value: 'all' as SourceFilter, label: 'All', count: skills.length },
                                { value: 'manual' as SourceFilter, label: 'Manual', count: manualCount },
                                { value: 'repo' as SourceFilter, label: 'Repo', count: repoCount },
                            ]
                        ).map((f) => (
                            <button
                                key={f.value}
                                type="button"
                                onClick={() => setFilter(f.value)}
                                className={cn(
                                    'rounded-md px-3 py-2 text-[13px] font-medium transition-colors outline-none cursor-pointer bg-transparent border-0',
                                    filter === f.value
                                        ? 'bg-[#E4E4E7] text-[#27272A]'
                                        : 'text-[#71717A] hover:text-[#52525B]',
                                )}
                            >
                                {f.label}
                                <span
                                    className={cn(
                                        'ml-1.5 text-[11px] px-1.5 py-0.5 rounded-full',
                                        filter === f.value
                                            ? 'bg-[#D4D4D8] text-[#27272A]'
                                            : 'bg-[#F4F4F5] text-[#71717A]',
                                    )}
                                >
                                    {f.count}
                                </span>
                            </button>
                        ))}
                    </div>
                </div>

                {/* Right: actions */}
                <div className="flex items-center gap-2">
                    <button
                        onClick={handleScan}
                        disabled={scanLoading}
                        className={cn(
                            'inline-flex items-center justify-center gap-2 rounded-lg border border-[#E4E4E7] bg-white px-4 py-2.5 text-[13px] font-medium text-[#27272A]',
                            'transition-colors hover:bg-[#F4F4F5] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer',
                        )}
                    >
                        {scanLoading ? (
                            <Loader2 className="h-3.5 w-3.5 animate-spin" />
                        ) : (
                            <RefreshCw className="h-3.5 w-3.5" />
                        )}
                        Scan Repos
                    </button>
                    <button
                        onClick={() => project && navigate(`/project/${project.name}/skills-init`)}
                        className="inline-flex items-center justify-center gap-2 rounded-lg border border-[#D4D4D8] bg-[#18181B] px-4 py-2.5 text-[13px] font-medium text-white transition-colors hover:bg-[#27272A] cursor-pointer"
                    >
                        <Plus className="h-3.5 w-3.5" />
                        Add Skill
                    </button>
                </div>
            </div>

            {/* Skill Grid */}
            {loading ? (
                <div className="grid grid-cols-2 gap-3 lg:grid-cols-3 pb-8">
                    {Array.from({ length: 4 }).map((_, i) => (
                        <SkeletonCard key={i} />
                    ))}
                </div>
            ) : filtered.length === 0 ? (
                <div className="flex flex-1 flex-col items-center justify-center pb-20 text-center">
                    <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl border border-dashed border-[#D4D4D8]">
                        <FileText className="h-5 w-5 text-[#8B8B94]" />
                    </div>
                    <h3 className="mb-1.5 text-[14px] font-semibold text-[#52525B]">
                        No skills found
                    </h3>
                    <p className="text-[13px] text-[#71717A]">
                        {skills.length === 0
                            ? 'Add skills manually or scan repositories to discover SKILL.md files.'
                            : 'No skills match your search or filter.'}
                    </p>
                </div>
            ) : (
                <div className="grid grid-cols-2 gap-3 lg:grid-cols-3 pb-8">
                    {filtered.map((skill) => (
                        <SkillCard
                            key={skill.id}
                            skill={skill}
                            onDelete={() => setDeleteTarget(skill)}
                        />
                    ))}
                </div>
            )}

            {/* Delete Confirm */}
            {deleteTarget && (
                <DeleteConfirm
                    name={deleteTarget.name || deleteTarget.slug}
                    loading={deleteLoading}
                    onClose={() => setDeleteTarget(null)}
                    onConfirm={handleDelete}
                />
            )}
        </div>
    );
}
