import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import axios from 'axios';
import { FormCard, PageContainer, PageHeader } from '../../components/layout';
import { useBreadcrumbs } from '../../hooks/useBreadcrumbs';
import { useToast } from '../../components/ui/Toast';
import { useWorkOrder, useUpdateWorkOrder } from '../../hooks/useWorkOrders';
import { OrdemServicoForm } from './components/OrdemServicoForm';
import type { CreateWorkOrderRequest } from '../../types/work-order.types';

export function OrdemServicoEditPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { showToast } = useToast();
  const [apiError, setApiError] = useState<string | null>(null);

  const { data: workOrder, isLoading, isError } = useWorkOrder(id ?? '');
  const breadcrumbs = useBreadcrumbs({ ':name': workOrder?.name ?? '' });
  const updateMutation = useUpdateWorkOrder();

  async function handleSubmit(data: CreateWorkOrderRequest) {
    if (!id) return;
    setApiError(null);
    const updateData = {
      code: data.code,
      name: data.name,
      description: data.description,
      contractItemId: data.contractItemId,
      projectIds: data.projectIds,
      reservedUst: data.reservedUst,
      startDate: data.startDate,
      endDate: data.endDate,
    };
    try {
      await updateMutation.mutateAsync({ id, data: updateData });
      showToast('Ordem de serviço atualizada com sucesso', 'success');
      navigate(`/ordens-servico/${id}`);
    } catch (err) {
      if (axios.isAxiosError(err)) {
        setApiError(err.response?.data?.message ?? 'Erro ao atualizar ordem de serviço.');
      } else {
        setApiError('Erro ao atualizar ordem de serviço.');
      }
    }
  }

  if (isLoading) {
    return (
      <PageContainer>
        <PageHeader title="Editar OS" breadcrumbs={breadcrumbs} />
        <div className="flex justify-center py-12">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-isis-blue border-t-transparent" />
        </div>
      </PageContainer>
    );
  }

  if (isError || !workOrder) {
    return (
      <PageContainer>
        <PageHeader title="Editar OS" breadcrumbs={breadcrumbs} />
        <div className="py-12 text-center text-text-muted">Ordem de serviço não encontrada</div>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      <PageHeader title="Editar OS" breadcrumbs={breadcrumbs} />
      <FormCard title={`Editar ${workOrder.code}`}>
        <OrdemServicoForm
          mode="edit"
          initialData={workOrder}
          initialStatus={workOrder.status}
          loading={updateMutation.isPending}
          apiError={apiError}
          onSubmit={handleSubmit}
          onCancel={() => navigate('/ordens-servico')}
        />
      </FormCard>
    </PageContainer>
  );
}
