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 { CompanyForm } from '@features/companies/components/CompanyForm';
import { companiesApi } from '@features/companies/api';
import type { CreateCompanyDto, UpdateCompanyDto } from '@features/companies/types';

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

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

    try {
      const company = await companiesApi.create(createData);
      showToast({
        type: 'success',
        title: 'Empresa creada',
        message: `${company.name} ha sido creada exitosamente.`,
      });
      navigate('/companies');
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Error al crear empresa';
      setError(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-6 p-6">
      <Breadcrumbs
        items={[
          { label: 'Empresas', href: '/companies' },
          { label: 'Nueva empresa' },
        ]}
      />

      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" onClick={() => navigate('/companies')}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Volver
        </Button>
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Nueva empresa</h1>
          <p className="text-sm text-gray-500">
            Crea una nueva empresa en el sistema
          </p>
        </div>
      </div>

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

            <CompanyForm
              onSubmit={handleSubmit}
              onCancel={() => navigate('/companies')}
              isLoading={isSubmitting}
            />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

export default CompanyCreatePage;
