import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import { Button } from '@components/atoms/Button';
import { Card, CardHeader, CardTitle, CardContent } from '@components/molecules/Card';
import { Alert } from '@components/molecules/Alert';
import { Breadcrumbs } from '@components/organisms/Breadcrumbs';
import { useToast } from '@components/organisms/Toast';
import { UserForm } from '@features/users/components/UserForm';
import { usersApi } from '@features/users/api';
import type { CreateUserDto, UpdateUserDto } from '@features/users/types';

export function UserCreatePage() {
  const navigate = useNavigate();
  const { showToast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (data: CreateUserDto | UpdateUserDto) => {
    const createData = data as CreateUserDto;
    setIsSubmitting(true);
    setError(null);

    try {
      const user = await usersApi.create(createData);
      showToast({
        type: 'success',
        title: 'Usuario creado',
        message: `${user.firstName} ${user.lastName} ha sido creado exitosamente.`,
      });
      navigate('/users');
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Error al crear usuario';
      setError(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-6 p-6">
      <Breadcrumbs
        items={[
          { label: 'Usuarios', href: '/users' },
          { label: 'Nuevo usuario' },
        ]}
      />

      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" onClick={() => navigate('/users')}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Volver
        </Button>
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Nuevo usuario</h1>
          <p className="text-sm text-gray-500">
            Crea una nueva cuenta de usuario
          </p>
        </div>
      </div>

      <div className="mx-auto max-w-2xl">
        <Card>
          <CardHeader>
            <CardTitle>Información del usuario</CardTitle>
          </CardHeader>
          <CardContent>
            {error && (
              <Alert
                variant="danger"
                title="Error"
                className="mb-4"
                onClose={() => setError(null)}
              >
                {error}
              </Alert>
            )}

            <UserForm
              onSubmit={handleSubmit}
              onCancel={() => navigate('/users')}
              isLoading={isSubmitting}
            />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
export default UserCreatePage;
