import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Save, GraduationCap } from 'lucide-react';
import { showLoading, updateToast } from '@/lib/toast';

interface EducationLevel {
    id: number;
    name: string;
    description?: string;
    created_at: string;
    updated_at: string;
}

interface Props {
    educationLevel: EducationLevel;
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Niveles Educativos', href: '/education-levels' },
];

export default function EditEducationLevel({ educationLevel }: Props) {
    const { data, setData, put, processing, errors } = useForm({
        name: educationLevel.name,
        description: educationLevel.description || '',
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const toastId = showLoading('Actualizando nivel educativo...');

        put(`/education-levels/${educationLevel.id}`, {
            onSuccess: () => {
                updateToast(toastId, 'success', 'Nivel educativo actualizado exitosamente');
            },
            onError: () => {
                updateToast(toastId, 'error', 'Error al actualizar el nivel educativo');
            }
        });
    };

    const currentBreadcrumbs: BreadcrumbItem[] = [
        ...breadcrumbs,
        { title: `Editar ${educationLevel.name}`, href: `/education-levels/${educationLevel.id}/edit` },
    ];

    return (
        <AppLayout breadcrumbs={currentBreadcrumbs}>
            <Head title={`Editar ${educationLevel.name}`} />

            <div className="flex h-full flex-1 flex-col gap-4 p-4 lg:gap-6 lg:p-6">
                <div className="flex flex-col gap-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-start gap-3 flex-1">
                            <div className="p-2 bg-emerald-100 dark:bg-emerald-900/20 rounded-lg flex-shrink-0">
                                <GraduationCap className="w-6 h-6 text-emerald-600 dark:text-emerald-400" />
                            </div>
                            <div className="min-w-0 flex-1">
                                <h1 className="text-xl font-bold text-slate-900 dark:text-white sm:text-2xl">
                                    Editar Nivel Educativo
                                </h1>
                                <p className="text-slate-600 dark:text-slate-400 mt-1 text-sm">
                                    Modifica la información del nivel educativo
                                </p>
                            </div>
                        </div>
                        <Button variant="outline" asChild className="ml-4 flex-shrink-0">
                            <Link href="/education-levels">
                                <ArrowLeft className="w-4 h-4 mr-2" />
                                Volver
                            </Link>
                        </Button>
                    </div>
                </div>

            <div className="max-w-4xl mx-auto">
                <Card>
                    <CardHeader>
                        <CardTitle>Información del Nivel Educativo</CardTitle>
                        <CardDescription>
                            Actualiza los datos del nivel educativo
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                    <form onSubmit={handleSubmit} className="space-y-6">
                        <div className="space-y-2">
                            <label htmlFor="name" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
                                Nombre *
                            </label>
                            <Input
                                id="name"
                                type="text"
                                value={data.name}
                                onChange={(e) => setData('name', e.target.value)}
                                placeholder="Ej: Educación Básica Primaria"
                                className={errors.name ? 'border-red-500' : ''}
                                required
                            />
                            {errors.name && (
                                <p className="text-sm text-red-600">{errors.name}</p>
                            )}
                        </div>

                        <div className="space-y-2">
                            <label htmlFor="description" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
                                Descripción
                            </label>
                            <Textarea
                                id="description"
                                value={data.description}
                                onChange={(e) => setData('description', e.target.value)}
                                placeholder="Describe las características de este nivel educativo..."
                                className={errors.description ? 'border-red-500' : ''}
                                rows={4}
                            />
                            {errors.description && (
                                <p className="text-sm text-red-600">{errors.description}</p>
                            )}
                        </div>

                        <div className="flex justify-end gap-4">
                            <Button variant="outline" type="button" asChild>
                                <Link href="/education-levels">
                                    Cancelar
                                </Link>
                            </Button>
                            <Button type="submit" disabled={processing}>
                                <Save className="w-4 h-4 mr-2" />
                                {processing ? 'Actualizando...' : 'Actualizar Nivel Educativo'}
                            </Button>
                        </div>
                    </form>
                </CardContent>
            </Card>
                </div>
            </div>
        </AppLayout>
    );
}
