import { Head, router, useForm } from '@inertiajs/react';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import InputError from '@/components/input-error';
import type { Category, System } from '@/types';

type Props = { systems: System[]; categories: Category[] };

export default function CreateKnowledgeBase({ systems, categories }: Props) {
    const { data, setData, post, processing, errors } = useForm({
        system_id: '',
        category_id: '',
        title: '',
        content: '',
        tags: [] as string[],
        is_published: false,
    });

    const [tagInput, setTagInput] = useState('');

    const filteredCategories = categories.filter(
        (c) => String(c.system_id) === data.system_id,
    );

    function addTag() {
        const tag = tagInput.trim();
        if (tag && !data.tags.includes(tag)) {
            setData('tags', [...data.tags, tag]);
        }
        setTagInput('');
    }

    function removeTag(tag: string) {
        setData(
            'tags',
            data.tags.filter((t) => t !== tag),
        );
    }

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        post('/admin/knowledge-base');
    }

    return (
        <>
            <Head title="New Article" />
            <div className="mx-auto max-w-2xl space-y-4 p-4">
                <h1 className="text-2xl font-bold">
                    New Knowledge Base Article
                </h1>
                <form onSubmit={handleSubmit}>
                    <Card>
                        <CardContent className="space-y-4 pt-6">
                            <div className="space-y-2">
                                <Label>System</Label>
                                <Select
                                    value={data.system_id}
                                    onValueChange={(v) => {
                                        setData('system_id', v);
                                        setData('category_id', '');
                                    }}
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select system" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {systems.map((s) => (
                                            <SelectItem
                                                key={s.id}
                                                value={String(s.id)}
                                            >
                                                {s.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <InputError message={errors.system_id} />
                            </div>
                            <div className="space-y-2">
                                <Label>Category (optional)</Label>
                                <Select
                                    value={data.category_id || '__none__'}
                                    onValueChange={(v) =>
                                        setData(
                                            'category_id',
                                            v === '__none__' ? '' : v,
                                        )
                                    }
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select category" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="__none__">
                                            None
                                        </SelectItem>
                                        {filteredCategories.map((c) => (
                                            <SelectItem
                                                key={c.id}
                                                value={String(c.id)}
                                            >
                                                {c.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="space-y-2">
                                <Label>Title</Label>
                                <Input
                                    value={data.title}
                                    onChange={(e) =>
                                        setData('title', e.target.value)
                                    }
                                />
                                <InputError message={errors.title} />
                            </div>
                            <div className="space-y-2">
                                <Label>Content</Label>
                                <textarea
                                    className="min-h-[200px] w-full rounded-md border bg-background px-3 py-2 text-sm"
                                    value={data.content}
                                    onChange={(e) =>
                                        setData('content', e.target.value)
                                    }
                                />
                                <InputError message={errors.content} />
                            </div>
                            <div className="space-y-2">
                                <Label>Tags</Label>
                                <div className="flex gap-2">
                                    <Input
                                        value={tagInput}
                                        onChange={(e) =>
                                            setTagInput(e.target.value)
                                        }
                                        placeholder="Add a tag"
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter') {
                                                e.preventDefault();
                                                addTag();
                                            }
                                        }}
                                    />
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={addTag}
                                    >
                                        Add
                                    </Button>
                                </div>
                                {data.tags.length > 0 && (
                                    <div className="mt-1 flex flex-wrap gap-1">
                                        {data.tags.map((tag) => (
                                            <span
                                                key={tag}
                                                className="inline-flex items-center gap-1 rounded bg-muted px-2 py-0.5 text-xs"
                                            >
                                                {tag}
                                                <button
                                                    type="button"
                                                    className="text-muted-foreground hover:text-foreground"
                                                    onClick={() =>
                                                        removeTag(tag)
                                                    }
                                                >
                                                    &times;
                                                </button>
                                            </span>
                                        ))}
                                    </div>
                                )}
                            </div>
                            <div className="flex items-center gap-2">
                                <Checkbox
                                    id="is_published"
                                    checked={data.is_published}
                                    onCheckedChange={(v) =>
                                        setData('is_published', !!v)
                                    }
                                />
                                <Label htmlFor="is_published">Publish</Label>
                            </div>
                            <div className="flex gap-3 pt-2">
                                <Button type="submit" disabled={processing}>
                                    Create
                                </Button>
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() =>
                                        router.visit('/admin/knowledge-base')
                                    }
                                >
                                    Cancel
                                </Button>
                            </div>
                        </CardContent>
                    </Card>
                </form>
            </div>
        </>
    );
}
