import { Head, useForm, Link } from '@inertiajs/react';
import React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import AppLayout from '@/layouts/app-layout';

// ─── Types ───────────────────────────────────────────────────────────────────

interface Employee {
    id: number;
    name: string;
    nip: string;
    position: string;
}

interface PageProps {
    employees: Employee[];
}

// ─── Component ───────────────────────────────────────────────────────────────

export default function Create({ employees }: PageProps) {
    const { data, setData, post, processing, errors } = useForm({
        employee_id: '',
        email: '',
        password: '',
        password_confirmation: '',
        role: '',
    });

    const selectedEmployee = employees.find((e) => String(e.id) === data.employee_id) ?? null;

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        post('/admin/users');
    };

    return (
        <AppLayout>
            <Head title="Buat Akun User" />

            <div className="p-4 md:p-8 w-full">
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">Buat Akun User</h2>
                        <p className="text-muted-foreground">
                            Hubungkan akun login dengan data karyawan yang sudah terdaftar.
                        </p>
                    </div>
                    <Button variant="outline" asChild>
                        <Link href="/admin/users">Kembali</Link>
                    </Button>
                </div>

                <Card className="max-w-xl">
                    <CardHeader>
                        <CardTitle>Form Akun Baru</CardTitle>
                    </CardHeader>
                    <Separator />
                    <CardContent className="pt-6">
                        <form onSubmit={submit} className="space-y-5">

                            {/* Pilih Karyawan */}
                            <div className="space-y-2">
                                <Label>
                                    Karyawan <span className="text-red-500">*</span>
                                </Label>
                                {employees.length === 0 ? (
                                    <div className="rounded-md border border-dashed p-4 text-center text-sm text-muted-foreground">
                                        Semua karyawan sudah memiliki akun.
                                    </div>
                                ) : (
                                    <Select onValueChange={(val) => setData('employee_id', val)}>
                                        <SelectTrigger>
                                            <SelectValue placeholder="Pilih karyawan..." />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {employees.map((emp) => (
                                                <SelectItem key={emp.id} value={String(emp.id)}>
                                                    <span className="font-medium">{emp.name}</span>
                                                    <span className="ml-2 text-muted-foreground text-xs">
                                                        ({emp.nip} — {emp.position})
                                                    </span>
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                )}
                                {errors.employee_id && (
                                    <p className="text-xs text-red-500">{errors.employee_id}</p>
                                )}
                            </div>

                            {/* Info karyawan terpilih */}
                            {selectedEmployee && (
                                <div className="rounded-md bg-muted/40 border px-4 py-3 text-sm">
                                    <p className="text-muted-foreground text-xs mb-1">Nama akun akan dibuat sebagai:</p>
                                    <p className="font-semibold">{selectedEmployee.name}</p>
                                </div>
                            )}

                            {/* Email */}
                            <div className="space-y-2">
                                <Label>
                                    Email <span className="text-red-500">*</span>
                                </Label>
                                <Input
                                    type="email"
                                    placeholder="nama@perusahaan.com"
                                    value={data.email}
                                    onChange={(e) => setData('email', e.target.value)}
                                />
                                {errors.email && (
                                    <p className="text-xs text-red-500">{errors.email}</p>
                                )}
                            </div>

                            <div className="space-y-2">
                                <Label>
                                    Password <span className="text-red-500">*</span>
                                </Label>
                                <Input
                                    type="password"
                                    placeholder="Minimal 8 karakter"
                                    value={data.password}
                                    onChange={(e) => setData('password', e.target.value)}
                                />
                                {errors.password && (
                                    <p className="text-xs text-red-500">{errors.password}</p>
                                )}
                            </div>

                            <div className="space-y-2">
                                <Label>
                                    Konfirmasi Password <span className="text-red-500">*</span>
                                </Label>
                                <Input
                                    type="password"
                                    value={data.password_confirmation}
                                    onChange={(e) => setData('password_confirmation', e.target.value)}
                                />
                            </div>

                            {/* Role */}
                            <div className="space-y-2">
                                <Label>
                                    Role <span className="text-red-500">*</span>
                                </Label>
                                <Select onValueChange={(val) => setData('role', val)}>
                                    <SelectTrigger>
                                        <SelectValue placeholder="Pilih role..." />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="employee">Employee</SelectItem>
                                        <SelectItem value="admin">Admin</SelectItem>
                                    </SelectContent>
                                </Select>
                                {errors.role && (
                                    <p className="text-xs text-red-500">{errors.role}</p>
                                )}
                            </div>

                            <Separator />

                            <div className="flex justify-start gap-3 pt-1">
                                <Button
                                    type="submit"
                                    disabled={processing || !data.employee_id}
                                >
                                    {processing ? 'Menyimpan...' : 'Buat Akun'}
                                </Button>
                                <Button type="button" variant="ghost" asChild>
                                    <Link href="/admin/users">Batal</Link>
                                </Button>
                            </div>

                        </form>
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
