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

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

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

    setIsSubmitting(true);
    setSubmitError(null);

    try {
      await partnersApi.update(id, data as UpdatePartnerDto);
      showToast({
        type: 'success',
        title: 'Partner actualizado',
        message: 'Los cambios han sido guardados exitosamente.',
      });
      navigate(`/partners/${id}`);
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Error al actualizar partner';
      setSubmitError(message);
    } finally {
      setIsSubmitting(false);
    }
  };

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

  if (error || !partner) {
    return (
      <div className="p-6">
        <ErrorEmptyState
          title="Partner no encontrado"
          description="No se pudo cargar la información del partner."
          onRetry={refresh}
        />
      </div>
    );
  }

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

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

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

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

export default PartnerEditPage;
