'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useValuationPredictForListing } from '@/lib/hooks/use-valuation';

interface AiEstimateButtonProps {
  listingId: string;
}

function formatPrice(num: number): string {
  if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(2)} ty`;
  if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(0)} trieu`;
  return num.toLocaleString('vi-VN');
}

export function AiEstimateButton({ listingId }: AiEstimateButtonProps) {
  const [showResult, setShowResult] = useState(false);
  const mutation = useValuationPredictForListing();

  const handleClick = () => {
    mutation.mutate(listingId, {
      onSuccess: () => setShowResult(true),
    });
  };

  if (showResult && mutation.data) {
    const result = mutation.data;
    const confidencePct = Math.round(result.confidence * 100);

    return (
      <Card className="border-primary/20 bg-primary/5">
        <CardHeader className="pb-2">
          <CardDescription>Gia uoc tinh AI</CardDescription>
          <CardTitle className="text-xl text-primary">
            {formatPrice(result.estimatedPriceVND)} VND
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-muted-foreground">Do tin cay</span>
            <span className="font-medium">{confidencePct}%</span>
          </div>
          <div className="h-1.5 rounded-full bg-muted">
            <div
              className="h-1.5 rounded-full bg-primary"
              style={{ width: `${confidencePct}%` }}
            />
          </div>
          <div className="flex items-center justify-between text-sm">
            <span className="text-muted-foreground">Khoang gia</span>
            <span className="font-medium">
              {formatPrice(result.priceRangeLow)} - {formatPrice(result.priceRangeHigh)}
            </span>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Button
      variant="outline"
      className="w-full gap-2"
      onClick={handleClick}
      disabled={mutation.isPending}
    >
      <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
        />
      </svg>
      {mutation.isPending ? 'Đang định giá...' : 'Định giá AI'}
    </Button>
  );
}
