"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { apiGet } from "@/lib/api";
import type { OwnerOperator } from "@/types";
import { PageHeader } from "@/components/ui/page-header";
import { OwnerOperatorForm } from "@/src/modules/owner-operators/components/owner-operator-form";

export default function EditOwnerOperatorPage() {
  const params = useParams<{ id: string }>();
  const [ownerOperator, setOwnerOperator] = useState<OwnerOperator | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!params?.id) return;
    apiGet<{ ownerOperator: OwnerOperator }>(`/api/owner-operators/${params.id}`)
      .then((data) => setOwnerOperator(data.ownerOperator))
      .catch((e) => setError(e?.message ?? "Failed to load owner operator"));
  }, [params?.id]);

  if (error) return <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>;
  if (!ownerOperator) return <div className="text-sm text-gray-500">Loading owner operator...</div>;

  return <div className="space-y-6"><PageHeader title={`Edit Owner Operator ${ownerOperator.businessName}`} subtitle="Update owner operator contact details, linked driver, linked truck, and notes." /><OwnerOperatorForm mode="edit" ownerOperator={ownerOperator} /></div>;
}
