'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-2xl font-bold sm:text-3xl">Định giá AI</h1>
        <p className="mt-2 text-muted-foreground">
          Sử dụng AI để ước tính giá trị bất động sản dựa trên dữ liệu thị trường
        </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">
              Không thể định giá. Vui lòng thử lại 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>
  );
}
