'use client';

import { useState } from 'react';
import { ValuationForm } from '@/components/valuation/valuation-form';
import { ValuationHistory } from '@/components/valuation/valuation-history';
import { ValuationResults } from '@/components/valuation/valuation-results';
import {
  useValuationPredict,
  useValuationHistory,
  useValuationDetail,
} from '@/lib/hooks/use-valuation';
import type { ValuationRequest, ValuationResult } from '@/lib/valuation-api';

export default function ValuationPage() {
  const [historyPage, setHistoryPage] = useState(1);
  const [selectedId, setSelectedId] = useState<string | null>(null);

  const predictMutation = useValuationPredict();
  const { data: historyData, isLoading: historyLoading } = useValuationHistory(historyPage);
  const { data: selectedResult } = useValuationDetail(selectedId ?? '');

  const currentResult: ValuationResult | undefined =
    predictMutation.data ?? selectedResult;

  const handleSubmit = (data: ValuationRequest) => {
    setSelectedId(null);
    predictMutation.mutate(data);
  };

  const handleSelectHistory = (id: string) => {
    setSelectedId(id);
  };

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-3xl font-bold">Dinh gia AI</h1>
        <p className="mt-2 text-muted-foreground">
          Su dung AI de uoc tinh gia tri bat dong san dua tren du lieu thi truong
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Form + Results */}
        <div className="space-y-6 lg:col-span-2">
          <ValuationForm
            onSubmit={handleSubmit}
            isLoading={predictMutation.isPending}
          />

          {predictMutation.isError && (
            <div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive">
              Khong the dinh gia. Vui long thu lai sau.
            </div>
          )}

          {currentResult && <ValuationResults result={currentResult} />}
        </div>

        {/* History sidebar */}
        <div>
          <ValuationHistory
            items={historyData?.data ?? []}
            total={historyData?.total ?? 0}
            page={historyPage}
            onPageChange={setHistoryPage}
            onSelect={handleSelectHistory}
            isLoading={historyLoading}
          />
        </div>
      </div>
    </div>
  );
}
