'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { useTranslation, formatPriceWithCurrency, translateCarName } from '@/lib/i18n';
import { useAuthStore } from '@/lib/store';
import { vehicleRequestsApi, VehicleRequestWithVehicles, DirectPurchasedCar } from '@/lib/api';
import SidebarLayout from '@/components/SidebarLayout';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || '';

// 이미지 URL 변환 (로컬 경로는 백엔드 URL 추가)
const getImageUrl = (url: string | undefined): string => {
  if (!url) return '';
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  // 로컬 경로인 경우 백엔드 URL 추가
  return `${API_BASE_URL}${url}`;
};

export default function MyRequestPage() {
  const router = useRouter();
  const { t, language } = useTranslation();
  const { user } = useAuthStore();

  const [requests, setRequests] = useState<VehicleRequestWithVehicles[]>([]);
  const [directPurchases, setDirectPurchases] = useState<DirectPurchasedCar[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedRequest, setExpandedRequest] = useState<number | null>(null);
  const [showDirectPurchases, setShowDirectPurchases] = useState(true);

  // Redirect if not logged in
  useEffect(() => {
    if (!user) {
      router.push('/login?redirect=/my-request');
    }
  }, [user, router]);

  // Load all vehicles (recommended + directly purchased)
  useEffect(() => {
    const loadVehicles = async () => {
      if (!user) return;

      try {
        setIsLoading(true);
        const data = await vehicleRequestsApi.getMyVehicles();
        setRequests(data.vehicle_requests);
        setDirectPurchases(data.direct_purchases);
        // Auto-expand first request if it has approved vehicles
        if (data.vehicle_requests.length > 0 && data.vehicle_requests[0].approved_vehicles.length > 0) {
          setExpandedRequest(data.vehicle_requests[0].request.id);
        }
      } catch (err) {
        console.error('Failed to load vehicles:', err);
        setError(language === 'ko' ? '차량 목록을 불러오는데 실패했습니다.' : 'Failed to load vehicles.');
      } finally {
        setIsLoading(false);
      }
    };

    loadVehicles();
  }, [user, language]);

  // Format date (mn uses en-US as mn-MN is not supported in most browsers)
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const locale = language === 'ko' ? 'ko-KR' : language === 'ru' ? 'ru-RU' : 'en-US';
    return date.toLocaleDateString(locale, {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  // Get status badge
  const getStatusBadge = (status: string) => {
    const statusConfig: Record<string, { color: string; label: string }> = {
      pending: { color: 'bg-yellow-100 text-yellow-800', label: t.pendingReview },
      reviewed: { color: 'bg-blue-100 text-blue-800', label: language === 'ko' ? '검토됨' : 'Reviewed' },
      completed: { color: 'bg-green-100 text-green-800', label: t.adminApproved },
    };

    const config = statusConfig[status] || statusConfig.pending;
    return (
      <span className={`px-3 py-1 rounded-full text-sm font-medium ${config.color}`}>
        {config.label}
      </span>
    );
  };

  // Format price
  const formatPrice = (priceKrw: number | undefined) => {
    return formatPriceWithCurrency(priceKrw, language);
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-800 mb-4">{t.loginRequired}</h2>
          <p className="text-gray-600 mb-6">{t.loginToRequest}</p>
          <Link
            href="/login?redirect=/my-request"
            className="bg-primary-600 text-white px-6 py-3 rounded-lg hover:bg-primary-700 transition"
          >
            {t.login}
          </Link>
        </div>
      </div>
    );
  }

  return (
    <SidebarLayout groupKey="quote">
      <div className="container mx-auto">
        {/* Header */}
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8 gap-4">
          <div>
            <h1 className="text-3xl font-bold text-gray-800">{t.myRequestTitle}</h1>
            <p className="text-gray-600 mt-1">{t.trackYourVehicle}</p>
          </div>
          <Link
            href="/vehicle-request"
            className="bg-primary-600 text-white px-6 py-2 rounded-lg hover:bg-primary-700 transition font-medium"
          >
            {t.newRequest}
          </Link>
        </div>

        {/* Loading State */}
        {isLoading && (
          <div className="flex justify-center items-center py-16">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
          </div>
        )}

        {/* Error State */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <p className="text-red-600">{error}</p>
          </div>
        )}

        {/* No Vehicles at all */}
        {!isLoading && !error && requests.length === 0 && directPurchases.length === 0 && (
          <div className="bg-white rounded-lg shadow-md p-12 text-center">
            <div className="text-gray-400 mb-4">
              <svg className="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
              </svg>
            </div>
            <h3 className="text-xl font-semibold text-gray-700 mb-2">{t.noRequestsYet}</h3>
            <Link
              href="/request"
              className="inline-block mt-4 bg-primary-600 text-white px-6 py-3 rounded-lg hover:bg-primary-700 transition font-medium"
            >
              {t.requestVehicle}
            </Link>
          </div>
        )}

        {/* Requests List */}
        {!isLoading && !error && requests.length > 0 && (
          <div className="space-y-6">
            {requests.map((item) => (
              <div key={item.request.id} className="bg-white rounded-lg shadow-md overflow-hidden">
                {/* Request Header */}
                <div
                  className="p-6 cursor-pointer hover:bg-gray-50 transition"
                  onClick={() => setExpandedRequest(expandedRequest === item.request.id ? null : item.request.id)}
                >
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <h3 className="text-lg font-semibold text-gray-800">
                          {translateCarName(item.request.maker_name, language)} - {translateCarName(item.request.model_name, language)}
                          {item.request.grade_name && ` (${translateCarName(item.request.grade_name, language)})`}
                        </h3>
                        {getStatusBadge(item.request.status)}
                      </div>
                      <div className="text-sm text-gray-500 space-y-1">
                        <p>
                          <span className="font-medium">{t.requestDate}:</span> {formatDate(item.request.created_at)}
                        </p>
                        {(item.request.year_from || item.request.year_to) && (
                          <p>
                            <span className="font-medium">{t.yearRange}:</span> {item.request.year_from || '-'} ~ {item.request.year_to || '-'}
                          </p>
                        )}
                        {(item.request.mileage_min || item.request.mileage_max) && (
                          <p>
                            <span className="font-medium">{t.mileageRange}:</span>{' '}
                            {item.request.mileage_min ? `${Math.round(item.request.mileage_min / 10000)}${t.tenThousandKm}` : '-'} ~{' '}
                            {item.request.mileage_max ? `${Math.round(item.request.mileage_max / 10000)}${t.tenThousandKm}` : '-'}
                          </p>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-4">
                      {item.approved_vehicles.length > 0 && (
                        <span className="bg-primary-100 text-primary-700 px-3 py-1 rounded-full text-sm font-medium">
                          {item.approved_vehicles.length} {t.approvedVehicles}
                        </span>
                      )}
                      <svg
                        className={`w-6 h-6 text-gray-400 transition-transform ${expandedRequest === item.request.id ? 'rotate-180' : ''}`}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                      </svg>
                    </div>
                  </div>
                </div>

                {/* Approved Vehicles */}
                {expandedRequest === item.request.id && item.approved_vehicles.length > 0 && (
                  <div className="border-t px-6 py-4 bg-gray-50">
                    <h4 className="text-md font-semibold text-gray-700 mb-4">{t.approvedVehicles}</h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {item.approved_vehicles.map((vehicle) => {
                        const carData = vehicle.car_data;
                        const priceInfo = formatPrice(carData?.final_price);
                        const isSoldout = carData?.soldout === true;
                        // Use car_id from vehicle or fallback to local_car_id in car_data
                        const carId = vehicle.car_id || carData?.local_car_id || carData?.id;

                        return (
                          <div key={vehicle.id} className={`bg-white rounded-lg shadow-sm overflow-hidden border transition-shadow ${isSoldout ? 'opacity-75' : 'hover:shadow-md'}`}>
                            {/* Clickable Vehicle Card */}
                            <Link href={carId ? `/cars/${carId}` : '#'} className={`block ${!carId ? 'pointer-events-none' : ''}`}>
                              {/* Vehicle Image */}
                              <div className="relative h-40 bg-gray-200">
                                {carData?.main_image ? (
                                  <Image
                                    src={getImageUrl(carData.main_image)}
                                    alt={carData.car_name || 'Vehicle'}
                                    fill
                                    className={`object-cover ${isSoldout ? 'grayscale' : ''}`}
                                    unoptimized
                                  />
                                ) : (
                                  <div className="absolute inset-0 flex items-center justify-center text-gray-400">
                                    <svg className="w-12 h-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                    </svg>
                                  </div>
                                )}
                                {/* Soldout Badge */}
                                {isSoldout && (
                                  <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                                    <span className="bg-red-600 text-white px-4 py-2 rounded-lg font-bold text-lg transform -rotate-12 shadow-lg">
                                      {language === 'ko' ? '판매완료' : 'SOLD OUT'}
                                    </span>
                                  </div>
                                )}
                              </div>

                              {/* Vehicle Info */}
                              <div className="p-4">
                                <h5 className="font-semibold text-gray-800 mb-2 line-clamp-2">
                                  {translateCarName(carData?.car_name, language)}
                                </h5>

                                <div className="text-sm text-gray-600 space-y-1 mb-3">
                                  <div className="flex justify-between">
                                    <span>{t.year}</span>
                                    <span>{carData?.year || '-'}</span>
                                  </div>
                                  <div className="flex justify-between">
                                    <span>{t.mileage}</span>
                                    <span>{carData?.mileage?.toLocaleString()} km</span>
                                  </div>
                                  <div className="flex justify-between">
                                    <span>{t.fuel}</span>
                                    <span>{translateCarName(carData?.fuel, language) || '-'}</span>
                                  </div>
                                </div>

                                <div className="border-t pt-3">
                                  <div className="text-primary-600 font-bold text-lg">
                                    {priceInfo.usdt}
                                  </div>
                                  <div className="text-gray-500 text-sm">
                                    {priceInfo.local}
                                  </div>
                                </div>
                              </div>
                            </Link>

                            {/* Action Buttons */}
                            <div className="px-4 pb-4 flex gap-2">
                              {isSoldout ? (
                                <div className="flex-1 bg-gray-400 text-white text-sm py-2 px-3 rounded-lg text-center font-medium">
                                  {language === 'ko' ? '판매완료' : 'Sold Out'}
                                </div>
                              ) : carId ? (
                                <>
                                  <button
                                    type="button"
                                    onClick={() => router.push(`/cars/${carId}?action=purchase`)}
                                    className="flex-1 bg-primary-600 text-white text-sm py-2 px-3 rounded-lg hover:bg-primary-700 transition font-medium"
                                  >
                                    {language === 'ko' ? '구매하기' : 'Purchase'}
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => {
                                      if (user?.is_dealer) {
                                        router.push(`/cars/${carId}?action=recommend`);
                                      } else {
                                        alert(language === 'ko'
                                          ? '딜러 회원만 지인 추천 기능을 사용할 수 있습니다. 딜러 등록을 원하시면 고객센터로 문의해주세요.'
                                          : 'Only dealer members can use the referral feature. Please contact customer service to register as a dealer.');
                                      }
                                    }}
                                    className="flex-1 bg-green-600 text-white text-sm py-2 px-3 rounded-lg hover:bg-green-700 transition font-medium"
                                  >
                                    {language === 'ko' ? '지인에게 추천' : 'Recommend to friend'}
                                  </button>
                                </>
                              ) : (
                                <div className="flex-1 bg-gray-300 text-gray-500 text-sm py-2 px-3 rounded-lg text-center font-medium">
                                  {language === 'ko' ? '차량 정보 없음' : 'Vehicle unavailable'}
                                </div>
                              )}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* No approved vehicles message */}
                {expandedRequest === item.request.id && item.approved_vehicles.length === 0 && (
                  <div className="border-t px-6 py-8 bg-gray-50 text-center">
                    <div className="text-gray-400 mb-2">
                      <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    </div>
                    <p className="text-gray-600">{t.waitingForQuote}</p>
                    <p className="text-sm text-gray-500 mt-1">{t.quoteWithin24Hours}</p>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {/* Directly Purchased Cars Section */}
        {!isLoading && !error && directPurchases.length > 0 && (
          <div className="mt-8">
            <div className="bg-white rounded-lg shadow-md overflow-hidden">
              {/* Section Header */}
              <div
                className="p-6 cursor-pointer hover:bg-gray-50 transition border-b"
                onClick={() => setShowDirectPurchases(!showDirectPurchases)}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center">
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
                      </svg>
                    </div>
                    <div>
                      <h3 className="text-lg font-semibold text-gray-800">
                        {language === 'ko' ? '직접 구매한 차량' : 'Directly Purchased Cars'}
                      </h3>
                      <p className="text-sm text-gray-500">
                        {language === 'ko' ? '배너에서 1CC로 정보를 구매한 차량' : 'Cars purchased with 1CC from banners'}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-4">
                    <span className="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm font-medium">
                      {directPurchases.length} {language === 'ko' ? '대' : 'cars'}
                    </span>
                    <svg
                      className={`w-6 h-6 text-gray-400 transition-transform ${showDirectPurchases ? 'rotate-180' : ''}`}
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </div>
                </div>
              </div>

              {/* Direct Purchases Grid */}
              {showDirectPurchases && (
                <div className="p-6 bg-gray-50">
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {directPurchases.map((purchase) => {
                      const carData = purchase.car_data;
                      const priceInfo = formatPrice(carData?.final_price);
                      const isSoldout = carData?.soldout === true;
                      const carId = purchase.car_id;

                      return (
                        <div key={purchase.id} className={`bg-white rounded-lg shadow-sm overflow-hidden border transition-shadow ${isSoldout ? 'opacity-75' : 'hover:shadow-md'}`}>
                          {/* Clickable Vehicle Card */}
                          <Link href={`/cars/${carId}`} className="block">
                            {/* Vehicle Image */}
                            <div className="relative h-40 bg-gray-200">
                              {carData?.main_image ? (
                                <Image
                                  src={getImageUrl(carData.main_image)}
                                  alt={carData.car_name || 'Vehicle'}
                                  fill
                                  className={`object-cover ${isSoldout ? 'grayscale' : ''}`}
                                  unoptimized
                                />
                              ) : (
                                <div className="absolute inset-0 flex items-center justify-center text-gray-400">
                                  <svg className="w-12 h-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                  </svg>
                                </div>
                              )}
                              {/* Soldout Badge */}
                              {isSoldout && (
                                <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                                  <span className="bg-red-600 text-white px-4 py-2 rounded-lg font-bold text-lg transform -rotate-12 shadow-lg">
                                    {language === 'ko' ? '판매완료' : 'SOLD OUT'}
                                  </span>
                                </div>
                              )}
                              {/* Direct Purchase Badge */}
                              <div className="absolute top-2 left-2">
                                <span className="bg-blue-600 text-white px-2 py-1 rounded text-xs font-medium">
                                  {purchase.cc_paid} CC
                                </span>
                              </div>
                            </div>

                            {/* Vehicle Info */}
                            <div className="p-4">
                              <h5 className="font-semibold text-gray-800 mb-2 line-clamp-2">
                                {translateCarName(carData?.car_name, language)}
                              </h5>

                              <div className="text-sm text-gray-600 space-y-1 mb-3">
                                <div className="flex justify-between">
                                  <span>{t.year}</span>
                                  <span>{carData?.year || '-'}</span>
                                </div>
                                <div className="flex justify-between">
                                  <span>{t.mileage}</span>
                                  <span>{carData?.mileage?.toLocaleString()} km</span>
                                </div>
                                <div className="flex justify-between">
                                  <span>{t.fuel}</span>
                                  <span>{translateCarName(carData?.fuel, language) || '-'}</span>
                                </div>
                              </div>

                              <div className="border-t pt-3">
                                <div className="text-primary-600 font-bold text-lg">
                                  {priceInfo.usdt}
                                </div>
                                <div className="text-gray-500 text-sm">
                                  {priceInfo.local}
                                </div>
                              </div>
                            </div>
                          </Link>

                          {/* Action Buttons */}
                          <div className="px-4 pb-4 flex gap-2">
                            {isSoldout ? (
                              <div className="flex-1 bg-gray-400 text-white text-sm py-2 px-3 rounded-lg text-center font-medium">
                                {language === 'ko' ? '판매완료' : 'Sold Out'}
                              </div>
                            ) : (
                              <>
                                <button
                                  type="button"
                                  onClick={() => router.push(`/cars/${carId}?action=purchase`)}
                                  className="flex-1 bg-primary-600 text-white text-sm py-2 px-3 rounded-lg hover:bg-primary-700 transition font-medium"
                                >
                                  {language === 'ko' ? '구매하기' : 'Purchase'}
                                </button>
                                <button
                                  type="button"
                                  onClick={() => {
                                    if (user?.is_dealer) {
                                      router.push(`/cars/${carId}?action=recommend`);
                                    } else {
                                      alert(language === 'ko'
                                        ? '딜러 회원만 지인 추천 기능을 사용할 수 있습니다.'
                                        : 'Only dealer members can use the referral feature.');
                                    }
                                  }}
                                  className="flex-1 bg-green-600 text-white text-sm py-2 px-3 rounded-lg hover:bg-green-700 transition font-medium"
                                >
                                  {language === 'ko' ? '지인에게 추천' : 'Recommend'}
                                </button>
                              </>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </SidebarLayout>
  );
}
