'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 } from '@/lib/i18n';
import { useAuthStore } from '@/lib/store';
import { vehicleRequestsApi, PurchasedVehicle } from '@/lib/api';
import SidebarLayout from '@/components/SidebarLayout';

// Shipping steps: 구매완료 - 인천항 - 텐진항(중국) - 자먼우드(몽골) - 울란바토르(몽골) - 통관 - 배송완료
const SHIPPING_STEPS = [
  { step: 1, key: 'step1Purchased', icon: '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' },
  { step: 2, key: 'step2IncheonPort', icon: 'M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4' },
  { step: 3, key: 'step3TianjinPort', icon: 'M13 10V3L4 14h7v7l9-11h-7z' },
  { step: 4, key: 'step4ZamynUud', icon: 'M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7' },
  { step: 5, key: 'step5Ulaanbaatar', icon: 'M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z M15 11a3 3 0 11-6 0 3 3 0 016 0z' },
  { step: 6, key: 'step6CustomsClearance', icon: 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z' },
  { step: 7, key: 'step7Delivered', icon: 'M5 13l4 4L19 7' },
];

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

  const [vehicles, setVehicles] = useState<PurchasedVehicle[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

      try {
        setIsLoading(true);
        const data = await vehicleRequestsApi.getPurchasedVehicles();
        setVehicles(data);
      } catch (err) {
        console.error('Failed to load vehicles:', err);
        setError(language === 'ko' ? '차량 정보를 불러오는데 실패했습니다.' : 'Failed to load vehicles.');
      } finally {
        setIsLoading(false);
      }
    };

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

  // Format date
  const formatDate = (dateString: string | null | undefined) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString(language === 'ko' ? 'ko-KR' : language === 'mn' ? 'mn-MN' : language === 'ru' ? 'ru-RU' : 'en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

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

  // Get step label
  const getStepLabel = (step: { key: string }) => {
    return (t as any)[step.key] || step.key;
  };

  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=/find-my-car"
            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="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">{t.findMyCarTitle}</h1>
          <p className="text-gray-600">{t.trackYourVehicle}</p>
        </div>

        {/* Route Visualization */}
        <div className="max-w-4xl mx-auto mb-8">
          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between relative">
              {/* Background Line */}
              <div className="absolute left-0 right-0 top-1/2 -translate-y-1/2 h-1 bg-gray-200 z-0"></div>

              {/* Steps */}
              {SHIPPING_STEPS.map((step, index) => (
                <div key={step.step} className="relative z-10 flex flex-col items-center">
                  <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
                    index === 0 ? 'bg-primary-600 text-white' : 'bg-gray-200 text-gray-500'
                  }`}>
                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={step.icon} />
                    </svg>
                  </div>
                  <span className={`mt-2 text-xs text-center max-w-[80px] ${
                    index === 0 ? 'text-primary-600 font-semibold' : 'text-gray-500'
                  }`}>
                    {getStepLabel(step)}
                  </span>
                </div>
              ))}
            </div>

            {/* Route Labels */}
            <div className="mt-6 flex justify-between text-sm text-gray-600">
              <div className="text-center">
                <p className="font-medium">{language === 'ko' ? '한국' : 'Korea'}</p>
                <p className="text-xs text-gray-400">{language === 'ko' ? '인천항' : 'Incheon'}</p>
              </div>
              <div className="text-center">
                <p className="font-medium">{language === 'ko' ? '중국' : 'China'}</p>
                <p className="text-xs text-gray-400">{language === 'ko' ? '텐진항' : 'Tianjin'}</p>
              </div>
              <div className="text-center">
                <p className="font-medium">{language === 'ko' ? '몽골' : 'Mongolia'}</p>
                <p className="text-xs text-gray-400">{language === 'ko' ? '울란바토르' : 'Ulaanbaatar'}</p>
              </div>
            </div>
          </div>
        </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 max-w-4xl mx-auto">
            <p className="text-red-600">{error}</p>
          </div>
        )}

        {/* No Vehicles */}
        {!isLoading && !error && vehicles.length === 0 && (
          <div className="max-w-2xl mx-auto 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.noPurchasedVehicles}</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>
        )}

        {/* Vehicles List */}
        {!isLoading && !error && vehicles.length > 0 && (
          <div className="max-w-4xl mx-auto space-y-6">
            {vehicles.map((vehicle) => (
              <div key={vehicle.id} className="bg-white rounded-lg shadow-md overflow-hidden">
                <div className="md:flex">
                  {/* Vehicle Image */}
                  <div className="md:w-1/3 relative h-48 md:h-auto bg-gray-200">
                    {vehicle.car_image ? (
                      <Image
                        src={vehicle.car_image}
                        alt={vehicle.car_name || 'Vehicle'}
                        fill
                        className="object-cover"
                        unoptimized
                      />
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center text-gray-400">
                        <svg className="w-16 h-16" 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>
                    )}
                  </div>

                  {/* Vehicle Info */}
                  <div className="md:w-2/3 p-6">
                    <div className="flex flex-col md:flex-row md:items-start justify-between gap-4 mb-4">
                      <div>
                        <h3 className="text-xl font-bold text-gray-800 mb-1">{vehicle.car_name}</h3>
                        <p className="text-sm text-gray-500">
                          {t.purchasedOn}: {formatDate(vehicle.purchased_at)}
                        </p>
                      </div>
                      <div className="text-right">
                        <div className="text-lg font-bold text-primary-600">
                          {formatPrice(vehicle.total_cost_krw).usdt}
                        </div>
                        <div className="text-sm text-gray-500">
                          {formatPrice(vehicle.total_cost_krw).local}
                        </div>
                      </div>
                    </div>

                    {/* Shipping Progress */}
                    <div className="mb-4">
                      <h4 className="text-sm font-semibold text-gray-700 mb-3">{t.shippingProgress}</h4>
                      <div className="flex items-center gap-2">
                        {SHIPPING_STEPS.map((step, index) => {
                          const isCompleted = vehicle.shipping_status >= step.step;
                          const isCurrent = vehicle.shipping_status === step.step;

                          return (
                            <div key={step.step} className="flex items-center">
                              {index > 0 && (
                                <div className={`w-8 h-1 ${isCompleted ? 'bg-green-500' : 'bg-gray-200'}`}></div>
                              )}
                              <div
                                className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-medium ${
                                  isCompleted
                                    ? isCurrent
                                      ? 'bg-green-500 text-white ring-4 ring-green-200'
                                      : 'bg-green-500 text-white'
                                    : 'bg-gray-200 text-gray-500'
                                }`}
                                title={getStepLabel(step)}
                              >
                                {isCompleted ? (
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                  </svg>
                                ) : (
                                  step.step
                                )}
                              </div>
                            </div>
                          );
                        })}
                      </div>
                      <p className="mt-2 text-sm text-green-600 font-medium">
                        {getStepLabel(SHIPPING_STEPS[vehicle.shipping_status - 1] || SHIPPING_STEPS[0])}
                      </p>
                    </div>

                    {/* Details Grid */}
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      {vehicle.current_location && (
                        <div>
                          <span className="text-gray-500">{t.currentLocation}:</span>
                          <span className="ml-2 font-medium text-gray-800">{vehicle.current_location}</span>
                        </div>
                      )}
                      {vehicle.estimated_arrival && (
                        <div>
                          <span className="text-gray-500">{t.estimatedArrival}:</span>
                          <span className="ml-2 font-medium text-gray-800">{formatDate(vehicle.estimated_arrival)}</span>
                        </div>
                      )}
                      {vehicle.car_type && (
                        <div>
                          <span className="text-gray-500">{language === 'ko' ? '차종' : 'Type'}:</span>
                          <span className="ml-2 font-medium text-gray-800">
                            {vehicle.car_type === 'small' ? t.smallCar : t.compactCar}
                          </span>
                        </div>
                      )}
                      {vehicle.delivered_at && (
                        <div>
                          <span className="text-gray-500">{t.step7Delivered}:</span>
                          <span className="ml-2 font-medium text-green-600">{formatDate(vehicle.delivered_at)}</span>
                        </div>
                      )}
                    </div>

                    {/* Cost Breakdown */}
                    {(vehicle.vehicle_price_krw || vehicle.domestic_cost_krw || vehicle.shipping_cost_usd) && (
                      <div className="mt-4 pt-4 border-t">
                        <h4 className="text-sm font-semibold text-gray-700 mb-2">{t.costTitle}</h4>
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-sm">
                          {vehicle.vehicle_price_krw && (
                            <div>
                              <span className="text-gray-500">{t.vehiclePrice}:</span>
                              <p className="font-medium">{formatPrice(vehicle.vehicle_price_krw).local}</p>
                            </div>
                          )}
                          {vehicle.domestic_cost_krw && (
                            <div>
                              <span className="text-gray-500">{t.domesticCosts}:</span>
                              <p className="font-medium">{formatPrice(vehicle.domestic_cost_krw).local}</p>
                            </div>
                          )}
                          {vehicle.shipping_cost_usd && (
                            <div>
                              <span className="text-gray-500">{t.shippingCost}:</span>
                              <p className="font-medium">${vehicle.shipping_cost_usd.toLocaleString()}</p>
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </SidebarLayout>
  );
}
