// src/features/contracts/components/ContractDetail.tsx
import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';

import { useContractDetail } from '@/features/contracts/hooks/useContractDetail';
import ContractDetailComponent from '@/features/contracts/components/ContractDetailComponent';
import ContractUpdateComponent from '@/features/contracts/components/ContractUpdateComponent';

export default function ContractDetail() {
  const { id } = useParams<{ id: string }>();
  const numericId = Number(id);
  const navigate = useNavigate();

  const { contract, loading, error, refresh } = useContractDetail(numericId);
  const [editing, setEditing] = useState(false);

  if (loading) return <p>Cargando…</p>;
  if (error || !contract) return <p className="text-red-600">{error}</p>;

  return (
    <div className="mx-auto max-w-xl space-y-6 p-4">
      {editing ? (
        <div className="container my-4">
          <div className="card shadow-sm">
            <div className="card-body">
              <div className="d-flex align-items-center my-4">
                <h2 className="h4 m-0">Modificar contrato</h2>
              </div>
              <ContractUpdateComponent
                contract={contract}
                onSaved={async () => {
                  setEditing(false);
                  await refresh();
                }}
                onCancel={() => setEditing(false)}
              />
            </div>
          </div>
        </div>
      ) : (
        <div className="container my-4">
          <div className="card shadow-sm">
            <div className="card-body">
              <div className="d-flex align-items-center my-4">
                <button
                  onClick={() => navigate(`/`)}
                  className="btn btn-outline-primary btn-sm me-3"
                >
                  &larr; Atrás
                </button>
                <h2 className="h4 m-0">Detalle de contrato</h2>
              </div>
              <ContractDetailComponent
                contract={contract}
                onEdit={() => setEditing(true)}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
