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 { PartnerForm } from '@features/partners/components/PartnerForm';
import { partnersApi } from '@features/partners/api';
import type { CreatePartnerDto, UpdatePartnerDto } from '@features/partners/types';

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

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

    try {
      const partner = await partnersApi.create(createData);
      showToast({
        type: 'success',
        title: 'Partner creado',
        message: `${partner.name} ha sido creado exitosamente.`,
      });
      navigate('/partners');
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Error al crear partner';
      setError(message);
    } finally {
      setIsSubmitting(false);
    }
  };

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

      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" onClick={() => navigate('/partners')}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Volver
        </Button>
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Nuevo partner</h1>
          <p className="text-sm text-gray-500">
            Crea un nuevo cliente, proveedor o contacto
          </p>
        </div>
      </div>

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

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

export default PartnerCreatePage;
