'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuthStore } from '@/lib/store';
import { useTranslation, translateCarName } from '@/lib/i18n';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

interface SharedVehicleData {
  share: {
    id: number;
    share_code: string;
    shared_price_krw: number;
    original_price_krw: number;
    markup_amount_krw: number;
    view_count: number;
    is_purchased: boolean;
    created_at: string;
  };
  vehicle: {
    id: number;
    car_id: number;
    maker: string;
    model: string;
    year: number;
    mileage: number;
    fuel_type: string;
    color: string;
    grade: string;
    image_url: string;
    performance_check_url: string;
    dealer_name: string;
    dealer_phone: string;
  };
  sharer: {
    name: string;
  };
}

export default function SharedVehiclePage() {
  const params = useParams();
  const router = useRouter();
  const { t, language } = useTranslation();
  const { user, token } = useAuthStore();

  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<SharedVehicleData | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [purchasing, setPurchasing] = useState(false);

  const shareCode = params.code as string;

  useEffect(() => {
    if (shareCode) {
      fetchSharedVehicle();
    }
  }, [shareCode]);

  const fetchSharedVehicle = async () => {
    try {
      const headers: Record<string, string> = {};
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const response = await fetch(`${API_BASE_URL}/api/share/${shareCode}`, {
        headers,
      });

      if (response.ok) {
        const result = await response.json();
        setData(result);
      } else {
        setError('Vehicle not found');
      }
    } catch (err) {
      console.error('Failed to fetch:', err);
      setError('Failed to load vehicle');
    } finally {
      setLoading(false);
    }
  };

  const handlePurchase = async () => {
    if (!user) {
      router.push('/login');
      return;
    }

    setPurchasing(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/share/${shareCode}/purchase`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (response.ok) {
        alert(language === 'ko' ? '구매 요청이 완료되었습니다!' : 'Purchase request submitted!');
        router.push('/my-request');
      } else {
        const err = await response.json();
        alert(err.detail || 'Purchase failed');
      }
    } catch (err) {
      console.error('Purchase failed:', err);
      alert('Purchase failed');
    } finally {
      setPurchasing(false);
    }
  };

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('ko-KR').format(price);
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">🚗</div>
          <h1 className="text-2xl font-bold text-gray-800 mb-2">
            {language === 'ko' ? '차량을 찾을 수 없습니다' : 'Vehicle not found'}
          </h1>
          <Link href="/" className="text-primary-600 hover:underline">
            {language === 'ko' ? '홈으로 돌아가기' : 'Go to Home'}
          </Link>
        </div>
      </div>
    );
  }

  const { share, vehicle, sharer } = data;

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4">
        <div className="max-w-4xl mx-auto">
          {/* Shared by badge */}
          <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
            <div className="flex items-center gap-2">
              <span className="text-2xl">🎁</span>
              <div>
                <p className="font-medium text-green-800">
                  {language === 'ko' ? `${sharer.name}님이 공유한 차량` : `Shared by ${sharer.name}`}
                </p>
                <p className="text-sm text-green-600">
                  {language === 'ko' ? '조회수: ' : 'Views: '}{share.view_count}
                </p>
              </div>
            </div>
          </div>

          {/* Vehicle Card */}
          <div className="bg-white rounded-xl shadow-lg overflow-hidden">
            {/* Image */}
            <div className="relative h-64 md:h-96 bg-gray-200">
              {vehicle.image_url ? (
                <img
                  src={vehicle.image_url}
                  alt={`${translateCarName(vehicle.maker, language)} ${translateCarName(vehicle.model, language)}`}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-gray-400">
                  <span className="text-6xl">🚗</span>
                </div>
              )}

              {share.is_purchased && (
                <div className="absolute top-4 right-4 bg-red-600 text-white px-4 py-2 rounded-lg font-bold">
                  {t.purchased}
                </div>
              )}
            </div>

            {/* Details */}
            <div className="p-6">
              <h1 className="text-2xl font-bold text-gray-800 mb-2">
                {translateCarName(vehicle.maker, language)} {translateCarName(vehicle.model, language)}
              </h1>
              <p className="text-gray-500 mb-4">{translateCarName(vehicle.grade, language)}</p>

              {/* Specs */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <div className="bg-gray-50 rounded-lg p-3 text-center">
                  <p className="text-sm text-gray-500">{t.year}</p>
                  <p className="font-semibold">{vehicle.year}</p>
                </div>
                <div className="bg-gray-50 rounded-lg p-3 text-center">
                  <p className="text-sm text-gray-500">{t.mileage}</p>
                  <p className="font-semibold">{formatPrice(vehicle.mileage)} km</p>
                </div>
                <div className="bg-gray-50 rounded-lg p-3 text-center">
                  <p className="text-sm text-gray-500">{t.fuel}</p>
                  <p className="font-semibold">{translateCarName(vehicle.fuel_type, language)}</p>
                </div>
                <div className="bg-gray-50 rounded-lg p-3 text-center">
                  <p className="text-sm text-gray-500">{t.color}</p>
                  <p className="font-semibold">{translateCarName(vehicle.color, language)}</p>
                </div>
              </div>

              {/* Price */}
              <div className="border-t border-gray-200 pt-6">
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <p className="text-sm text-gray-500">{t.sharedPrice}</p>
                    <p className="text-3xl font-bold text-primary-600">
                      {formatPrice(share.shared_price_krw)} {language === 'ko' ? '원' : 'KRW'}
                    </p>
                  </div>
                  {share.markup_amount_krw > 0 && (
                    <div className="text-right">
                      <p className="text-sm text-gray-500 line-through">
                        {t.originalPrice}: {formatPrice(share.original_price_krw)}원
                      </p>
                    </div>
                  )}
                </div>

                {/* Actions */}
                {!share.is_purchased ? (
                  <div className="space-y-3">
                    <button
                      onClick={handlePurchase}
                      disabled={purchasing}
                      className="w-full py-4 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 disabled:opacity-50 transition"
                    >
                      {purchasing ? (
                        <span className="flex items-center justify-center gap-2">
                          <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                          {t.loading}
                        </span>
                      ) : (
                        language === 'ko' ? '구매 신청하기' : 'Request Purchase'
                      )}
                    </button>

                    {!user && (
                      <p className="text-sm text-center text-gray-500">
                        {language === 'ko' ? '구매하려면 로그인이 필요합니다' : 'Login required to purchase'}
                      </p>
                    )}
                  </div>
                ) : (
                  <div className="bg-gray-100 rounded-lg p-4 text-center text-gray-600">
                    {language === 'ko' ? '이미 판매된 차량입니다' : 'This vehicle has been sold'}
                  </div>
                )}
              </div>

              {/* Dealer Info */}
              {vehicle.dealer_name && (
                <div className="mt-6 pt-6 border-t border-gray-200">
                  <h3 className="font-semibold text-gray-800 mb-2">{t.dealerContact}</h3>
                  <p className="text-gray-600">{vehicle.dealer_name}</p>
                  {vehicle.dealer_phone && (
                    <p className="text-gray-600">{vehicle.dealer_phone}</p>
                  )}
                </div>
              )}

              {/* Performance Check */}
              {vehicle.performance_check_url && (
                <div className="mt-4">
                  <a
                    href={vehicle.performance_check_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 text-primary-600 hover:underline"
                  >
                    <span>📋</span>
                    {t.viewPerformanceReport}
                  </a>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
