import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import { Button } from '@components/atoms/Button';
import { Spinner } from '@components/atoms/Spinner';
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 { ErrorEmptyState } from '@components/templates/EmptyState';
import { CompanyForm } from '@features/companies/components/CompanyForm';
import { useCompany } from '@features/companies/hooks';
import { companiesApi } from '@features/companies/api';
import type { CreateCompanyDto, UpdateCompanyDto } from '@features/companies/types';

export function CompanyEditPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { company, isLoading, error, refresh } = useCompany(id);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  const handleSubmit = async (data: CreateCompanyDto | UpdateCompanyDto) => {
    if (!id) return;

    setIsSubmitting(true);
    setSubmitError(null);

    try {
      await companiesApi.update(id, data as UpdateCompanyDto);
      showToast({
        type: 'success',
        title: 'Empresa actualizada',
        message: 'Los cambios han sido guardados exitosamente.',
      });
      navigate(`/companies/${id}`);
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Error al actualizar empresa';
      setSubmitError(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex h-96 items-center justify-center">
        <Spinner size="lg" />
      </div>
    );
  }

  if (error || !company) {
    return (
      <div className="p-6">
        <ErrorEmptyState
          title="Empresa no encontrada"
          description="No se pudo cargar la información de la empresa."
          onRetry={refresh}
        />
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6">
      <Breadcrumbs
        items={[
          { label: 'Empresas', href: '/companies' },
          { label: company.name, href: `/companies/${id}` },
          { label: 'Editar' },
        ]}
      />

      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" onClick={() => navigate(`/companies/${id}`)}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Volver
        </Button>
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Editar empresa</h1>
          <p className="text-sm text-gray-500">
            Modifica la información de {company.name}
          </p>
        </div>
      </div>

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

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

export default CompanyEditPage;
