'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

import PurchaseRequestForm from '@/components/pages/purchase/form/request/PurchaseRequestForm';

import { PurchaseApi } from '@/services/api/purchase';
import { isResponseError } from '@/lib/api-helper';

import { Purchase } from '@/types/api/purchase/purchase';

// TODO: delete dummy data
const DUMMY_PURCHASE_DETAIL: Purchase = {
  id: 1,
  pr_number: 'PR-001',
  po_number: 'PO-001',
  po_date: '2024-01-15',
  supplier: {
    id: 1,
    name: 'Supplier A',
    address: '123 Main St, Cityville',
    account_number: 'ACC-12345',
    alias: 'SupA',
    category: 'Electronics',
    type: 'Local',
    phone: '555-1234',
    email: 'email@.com',
    npwp: '12.345.678.9-012.345',
    pic: 'John Doe',
    balance: 1000000,
    hatchery: 'N/A',
    due_date: 30,
    created_at: '2024-01-10T10:00:00Z',
    updated_at: '2024-01-12T12:00:00Z',
    created_user: {
      id: 2,
      id_user: 2,
      email: 'a@email.com',
      name: 'Admin User',
    },
  },
  credit_term: 30,
  due_date: '2024-02-14',
  grand_total: 1500000,
  notes: 'Urgent delivery required',
  deleted_at: null,
  created_at: '2024-01-10T10:00:00Z',
  updated_at: '2024-01-12T12:00:00Z',
  created_by: 2,
  created_user: {
    id: 2,
    id_user: 2,
    email: 'a@email.com',
    name: 'Admin User',
  },
};

const PurchaseDetail = () => {
  const router = useRouter();
  const searchParams = useSearchParams();

  const purchaseId = searchParams.get('purchaseId');

  const { data: purchase, isLoading: isLoadingPurchase } = useSWR(
    purchaseId,
    (id: number) => PurchaseApi.getSingle(id)
  );

  if (!purchaseId) {
    router.back();

    return (
      <div className='w-full flex flex-row justify-center items-center p-4'>
        <span className='loading loading-spinner loading-xl' />
      </div>
    );
  }

  // TODO: remove dummy data and integrate with real API
  if (
    !isLoadingPurchase &&
    (!purchase || (isResponseError(purchase) && !DUMMY_PURCHASE_DETAIL))
  ) {
    router.replace('/404');
    return;
  }

  return (
    <div className='w-full p-4 flex flex-row justify-center'>
      {isLoadingPurchase && (
        <span className='loading loading-spinner loading-xl' />
      )}
      {/* {!isLoadingPurchase && isResponseSuccess(purchase) && (
        <PurchaseRequestForm type='detail' initialValues={purchase.data} />
      )} */}

      {/* TODO: remove this dummy data and integrate to real API */}
      <PurchaseRequestForm
        type='detail'
        initialValues={DUMMY_PURCHASE_DETAIL}
      />
    </div>
  );
};

export default PurchaseDetail;
