import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Loader2, Plus, ArrowLeft } from 'lucide-react';
import { skillCreate } from '@/client';
import { useProject } from '@/contexts';

export function SkillsInit() {
    const { project } = useProject();
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [slug, setSlug] = useState('');
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [content, setContent] = useState('');

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!project?.name || !slug) return;
        setLoading(true);
        try {
            await skillCreate({
                path: { project_name: project.name },
                body: {
                    slug,
                    name: name || undefined,
                    description: description || undefined,
                    content: content || '',
                },
            });
            toast.success(`Skill "${name || slug}" created`);
            navigate(`/project/${project.name}/skills`);
        } catch (err: unknown) {
            toast.error(
                (err as { response?: { data?: { message?: string } } })
                    ?.response?.data?.message || 'Failed to create skill',
            );
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="mx-auto flex min-h-full w-full max-w-[680px] flex-col gap-6 px-6 pt-6 pb-8">
            {/* Back */}
            {project && (
                <button
                    onClick={() => navigate(`/project/${project.name}/skills`)}
                    className="flex items-center gap-1.5 text-[13px] text-[#71717A] hover:text-[#27272A] transition-colors bg-transparent border-0 cursor-pointer self-start"
                >
                    <ArrowLeft className="h-3.5 w-3.5" />
                    Back to Skills
                </button>
            )}

            {/* Page Header */}
            <div className="border-b border-[#E4E4E7] pb-4">
                <div className="flex items-center gap-3">
                    <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-[rgba(5,150,105,0.08)]">
                        <Plus className="h-4 w-4 text-[#18181B]" />
                    </div>
                    <div>
                        <h1 className="text-[17px] font-semibold tracking-tight text-[#18181B]">
                            New Skill
                        </h1>
                        <p className="text-[13px] text-[#71717A]">
                            Add a skill to this project
                        </p>
                    </div>
                </div>
            </div>

            {/* Form */}
            <form onSubmit={handleSubmit} className="space-y-6">
                {/* Slug */}
                <div className="space-y-1.5">
                    <Label
                        htmlFor="slug"
                        className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]"
                    >
                        Slug
                    </Label>
                    <Input
                        id="slug"
                        value={slug}
                        onChange={(e) =>
                            setSlug(
                                e.target.value
                                    .toLowerCase()
                                    .replace(/[^a-z0-9/_-]/g, ''),
                            )
                        }
                        placeholder="coding/code-review"
                        className="h-10 font-mono text-[13px] border-[#E4E4E7] focus:border-[#D4D4D8]"
                        required
                    />
                    <p className="text-[12px] text-[#8B8B94]">
                        Unique identifier, use / to group skills
                    </p>
                </div>

                {/* Name */}
                <div className="space-y-1.5">
                    <Label
                        htmlFor="name"
                        className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]"
                    >
                        Display Name
                    </Label>
                    <Input
                        id="name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        placeholder="Code Review Agent"
                        className="h-10 border-[#E4E4E7] focus:border-[#D4D4D8]"
                    />
                </div>

                {/* Description */}
                <div className="space-y-1.5">
                    <Label
                        htmlFor="desc"
                        className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]"
                    >
                        Description
                    </Label>
                    <Input
                        id="desc"
                        value={description}
                        onChange={(e) => setDescription(e.target.value)}
                        placeholder="Reviews pull requests with AI"
                        className="h-10 border-[#E4E4E7] focus:border-[#D4D4D8]"
                    />
                </div>

                {/* Content */}
                <div className="space-y-1.5">
                    <Label
                        htmlFor="content"
                        className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]"
                    >
                        Content (SKILL.md)
                    </Label>
                    <Textarea
                        id="content"
                        value={content}
                        onChange={(e) => setContent(e.target.value)}
                        placeholder={'# Code Review\n\nYou are an expert code reviewer...'}
                        rows={12}
                        className="font-mono text-[13px] leading-relaxed border-[#E4E4E7] focus:border-[#D4D4D8]"
                    />
                    <p className="text-[12px] text-[#8B8B94]">
                        Markdown describing when and how to use this skill.
                    </p>
                </div>

                {/* Actions */}
                <div className="flex items-center justify-end gap-2 pt-2 border-t border-[#E4E4E7]">
                    <button
                        type="button"
                        onClick={() =>
                            project && navigate(`/project/${project.name}/skills`)
                        }
                        className="px-4 py-2.5 rounded-lg border border-[#E4E4E7] bg-white text-[13px] font-medium text-[#27272A] hover:bg-[#F4F4F5] transition-colors cursor-pointer"
                    >
                        Cancel
                    </button>
                    <button
                        type="submit"
                        disabled={loading || !slug}
                        className="inline-flex items-center justify-center gap-2 px-5 py-2.5 rounded-lg border border-[#D4D4D8] bg-[#18181B] text-[13px] font-medium text-white transition-colors hover:bg-[#27272A] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                    >
                        {loading && <Loader2 className="h-4 w-4 animate-spin" />}
                        Create Skill
                    </button>
                </div>
            </form>
        </div>
    );
}
