'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useTranslation, translateCarName } from '@/lib/i18n';
import { useAuthStore } from '@/lib/store';
import { carmodooApi, vehicleRequestsApi, ccApi, CarmodooMaker, CarmodooModel } from '@/lib/api';
import SidebarLayout from '@/components/SidebarLayout';

const QUOTE_REQUEST_COST = 1; // 1 CC for quote request

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

  // Form state
  const [selectedMaker, setSelectedMaker] = useState<string>('');
  const [selectedMakerName, setSelectedMakerName] = useState<string>('');
  const [selectedModel, setSelectedModel] = useState<string>('');
  const [selectedModelName, setSelectedModelName] = useState<string>('');
  const [selectedGrade, setSelectedGrade] = useState<string>('');
  const [selectedGradeName, setSelectedGradeName] = useState<string>('');
  const [yearFrom, setYearFrom] = useState<string>('');
  const [yearTo, setYearTo] = useState<string>('');
  const [mileageMin, setMileageMin] = useState<string>('');
  const [mileageMax, setMileageMax] = useState<string>('');
  const [selectedFuel, setSelectedFuel] = useState<string>('');
  const [displacementMin, setDisplacementMin] = useState<string>('');
  const [displacementMax, setDisplacementMax] = useState<string>('');

  // Data state
  const [makers, setMakers] = useState<CarmodooMaker[]>([]);
  const [models, setModels] = useState<CarmodooModel[]>([]);
  const [grades, setGrades] = useState<{ code: string; name: string }[]>([]);

  // UI state
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [loadingMakers, setLoadingMakers] = useState(true);
  const [loadingModels, setLoadingModels] = useState(false);
  const [loadingGrades, setLoadingGrades] = useState(false);
  const [validationError, setValidationError] = useState<string>('');
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [ccBalance, setCcBalance] = useState<number>(0);
  const [showConfirmModal, setShowConfirmModal] = useState(false);

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

  // Load CC balance
  useEffect(() => {
    if (user) {
      ccApi.getBalance()
        .then((data) => setCcBalance(data.cc_balance || 0))
        .catch(console.error);
    }
  }, [user]);

  // Load makers on mount
  useEffect(() => {
    const loadMakers = async () => {
      try {
        const data = await carmodooApi.getMakers();
        setMakers(data);
      } catch (error) {
        console.error('Failed to load makers:', error);
      } finally {
        setLoadingMakers(false);
      }
    };
    loadMakers();
  }, []);

  // Load models when maker changes
  useEffect(() => {
    if (selectedMaker) {
      setLoadingModels(true);
      setSelectedModel('');
      setSelectedModelName('');
      setSelectedGrade('');
      setSelectedGradeName('');
      carmodooApi.getModels(selectedMaker)
        .then(setModels)
        .catch(console.error)
        .finally(() => setLoadingModels(false));
    } else {
      setModels([]);
      setSelectedModel('');
      setSelectedModelName('');
    }
  }, [selectedMaker]);

  // Load grades when model changes
  useEffect(() => {
    if (selectedMaker && selectedModel) {
      setLoadingGrades(true);
      setSelectedGrade('');
      setSelectedGradeName('');
      carmodooApi.getGrades(selectedMaker, selectedModel)
        .then(setGrades)
        .catch((error) => {
          console.error('Failed to load grades:', error);
          setGrades([]);
        })
        .finally(() => setLoadingGrades(false));
    } else {
      setGrades([]);
      setSelectedGrade('');
      setSelectedGradeName('');
    }
  }, [selectedMaker, selectedModel]);

  // Handle maker selection
  const handleMakerChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const code = e.target.value;
    setSelectedMaker(code);
    const maker = makers.find(m => m.code === code);
    setSelectedMakerName(maker?.name || '');
  };

  // Handle model selection
  const handleModelChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const code = e.target.value;
    setSelectedModel(code);
    const model = models.find(m => m.code === code);
    setSelectedModelName(model?.name || '');
  };

  // Handle grade selection
  const handleGradeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const code = e.target.value;
    setSelectedGrade(code);
    const grade = grades.find(g => g.code === code);
    setSelectedGradeName(grade?.name || '');
  };

  // Check if required fields are filled
  const isFormValid = () => {
    return selectedMaker && selectedModel;
  };

  // Handle form submission - show confirmation modal
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    // Validate required fields
    if (!selectedMaker) {
      setValidationError(language === 'ko' ? '제조사를 선택해주세요.' : 'Please select a maker.');
      return;
    }
    if (!selectedModel) {
      setValidationError(language === 'ko' ? '모델을 선택해주세요.' : 'Please select a model.');
      return;
    }

    setValidationError('');
    // Show confirmation modal instead of submitting directly
    setShowConfirmModal(true);
  };

  // Confirm and submit the request
  const handleConfirmSubmit = async () => {
    setShowConfirmModal(false);
    setIsSubmitting(true);

    try {
      await vehicleRequestsApi.createRequest({
        maker_code: selectedMaker,
        maker_name: selectedMakerName,
        model_code: selectedModel,
        model_name: selectedModelName,
        grade_code: selectedGrade || undefined,
        grade_name: selectedGradeName || undefined,
        year_from: yearFrom ? parseInt(yearFrom) : undefined,
        year_to: yearTo ? parseInt(yearTo) : undefined,
        mileage_min: mileageMin ? parseInt(mileageMin) * 10000 : undefined,
        mileage_max: mileageMax ? parseInt(mileageMax) * 10000 : undefined,
        fuel: selectedFuel || undefined,
        displacement_min: displacementMin ? parseInt(displacementMin) : undefined,
        displacement_max: displacementMax ? parseInt(displacementMax) : undefined,
      });

      // Update CC balance after successful submission
      setCcBalance((prev) => prev - QUOTE_REQUEST_COST);
      setSubmitSuccess(true);
    } catch (error: any) {
      console.error('Failed to submit request:', error);
      const errorMessage = error?.response?.data?.detail || error?.message || 'Unknown error';
      console.error('Error details:', errorMessage);
      setValidationError(
        language === 'ko'
          ? `요청 제출에 실패했습니다: ${errorMessage}`
          : `Failed to submit request: ${errorMessage}`
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  // Reset form
  const handleNewRequest = async () => {
    setSelectedMaker('');
    setSelectedMakerName('');
    setSelectedModel('');
    setSelectedModelName('');
    setSelectedGrade('');
    setSelectedGradeName('');
    setYearFrom('');
    setYearTo('');
    setMileageMin('');
    setMileageMax('');
    setSelectedFuel('');
    setDisplacementMin('');
    setDisplacementMax('');
    setSubmitSuccess(false);
    setValidationError('');

    // Refresh CC balance
    try {
      const data = await ccApi.getBalance();
      setCcBalance(data.cc_balance || 0);
    } catch (error) {
      console.error('Failed to refresh CC balance:', error);
    }
  };

  // Generate year options (2010 ~ current year)
  const currentYear = new Date().getFullYear();
  const yearOptions = Array.from({ length: currentYear - 2009 }, (_, i) => currentYear - i);

  // Mileage options (만km)
  const mileageOptions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20];

  // Fuel type options
  const fuelOptions = [
    { value: '휘발유', label: { ko: '휘발유', en: 'Gasoline', mn: 'Бензин', ru: 'Бензин' } },
    { value: '경유', label: { ko: '디젤', en: 'Diesel', mn: 'Дизель', ru: 'Дизель' } },
    { value: '하이브리드', label: { ko: '하이브리드', en: 'Hybrid', mn: 'Гибрид', ru: 'Гибрид' } },
    { value: 'LPG', label: { ko: 'LPG', en: 'LPG', mn: 'LPG', ru: 'LPG' } },
    { value: '전기', label: { ko: '전기', en: 'Electric', mn: 'Цахилгаан', ru: 'Электро' } },
  ];

  // Displacement options (cc)
  const displacementOptions = [1000, 1500, 2000, 2500, 3000, 3500, 4000, 5000];

  if (!user) {
    return (
      <SidebarLayout groupKey="quote">
        <div className="flex items-center justify-center min-h-[60vh]">
          <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=/vehicle-request"
              className="bg-primary-600 text-white px-6 py-3 rounded-lg hover:bg-primary-700 transition"
            >
              {t.login}
            </Link>
          </div>
        </div>
      </SidebarLayout>
    );
  }

  // Success screen
  if (submitSuccess) {
    return (
      <SidebarLayout groupKey="quote">
        <div className="max-w-2xl mx-auto bg-white rounded-lg shadow-md p-8 text-center">
          {/* Success Icon */}
          <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg className="w-10 h-10 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>

          {/* Success Title */}
          <h1 className="text-2xl font-bold text-gray-800 mb-4">
            {t.requestSubmitted}
          </h1>

          {/* 24 Hour Promise */}
          <div className="bg-primary-50 border border-primary-200 rounded-lg p-6 mb-6">
            <div className="flex items-center justify-center mb-3">
              <svg className="w-6 h-6 text-primary-600 mr-2" 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>
              <span className="text-lg font-semibold text-primary-700">
                {t.quoteWithin24Hours}
              </span>
            </div>
            <p className="text-gray-600 text-sm">
              {t.reviewingRequest}
            </p>
          </div>

          {/* Summary */}
          <div className="bg-gray-50 rounded-lg p-4 mb-6 text-left">
            <h3 className="font-semibold text-gray-700 mb-3">{t.requestSummary}</h3>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-500">{t.maker}</span>
                <span className="font-medium">{translateCarName(selectedMakerName, language)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">{t.model}</span>
                <span className="font-medium">{translateCarName(selectedModelName, language)}</span>
              </div>
              {selectedGradeName && (
                <div className="flex justify-between">
                  <span className="text-gray-500">{t.grade}</span>
                  <span className="font-medium">{translateCarName(selectedGradeName, language)}</span>
                </div>
              )}
              {(yearFrom || yearTo) && (
                <div className="flex justify-between">
                  <span className="text-gray-500">{t.yearRange}</span>
                  <span className="font-medium">
                    {yearFrom || '-'} ~ {yearTo || '-'}
                  </span>
                </div>
              )}
              {(mileageMin || mileageMax) && (
                <div className="flex justify-between">
                  <span className="text-gray-500">{t.mileageRange}</span>
                  <span className="font-medium">
                    {mileageMin ? `${mileageMin}${t.tenThousandKm}` : '-'} ~ {mileageMax ? `${mileageMax}${t.tenThousandKm}` : '-'}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <Link
              href="/my-request"
              className="bg-primary-600 text-white px-6 py-3 rounded-lg hover:bg-primary-700 transition font-medium"
            >
              {t.viewMyRequests}
            </Link>
            <button
              onClick={handleNewRequest}
              className="bg-gray-100 text-gray-700 px-6 py-3 rounded-lg hover:bg-gray-200 transition font-medium"
            >
              {t.newRequest}
            </button>
          </div>
        </div>
      </SidebarLayout>
    );
  }

  return (
    <SidebarLayout groupKey="quote">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">{t.requestVehicle}</h1>
          <p className="text-gray-600">{t.findYourDreamCar}</p>
        </div>

        {/* 24 Hour Promise Banner */}
        <div className="bg-primary-50 border border-primary-200 rounded-lg p-4 mb-6">
          <div className="flex items-center justify-center">
            <svg className="w-6 h-6 text-primary-600 mr-2 flex-shrink-0" 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>
            <span className="text-primary-700 font-semibold">
              {t.quoteWithin24Hours}
            </span>
          </div>
        </div>

        {/* Search Form */}
        <form onSubmit={handleSubmit} className="bg-white rounded-lg shadow-md p-6 mb-8">
          {/* Row 1: Maker, Model, Grade */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
            {/* Maker */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.maker} <span className="text-red-500">*</span>
              </label>
              <select
                value={selectedMaker}
                onChange={handleMakerChange}
                disabled={loadingMakers || isSubmitting}
                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
              >
                <option value="">{t.selectMaker}</option>
                {makers.map((maker) => (
                  <option key={maker.code} value={maker.code}>
                    {translateCarName(maker.name, language)}
                  </option>
                ))}
              </select>
            </div>

            {/* Model */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.model} <span className="text-red-500">*</span>
              </label>
              <select
                value={selectedModel}
                onChange={handleModelChange}
                disabled={!selectedMaker || loadingModels || isSubmitting}
                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
              >
                <option value="">{t.selectModel}</option>
                {models.map((model) => (
                  <option key={model.code} value={model.code}>
                    {translateCarName(model.name, language)}
                  </option>
                ))}
              </select>
            </div>

            {/* Grade */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.grade}
              </label>
              <select
                value={selectedGrade}
                onChange={handleGradeChange}
                disabled={!selectedModel || loadingGrades || isSubmitting}
                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
              >
                <option value="">{loadingGrades ? (language === 'ko' ? '로딩중...' : 'Loading...') : t.allGrades}</option>
                {grades.map((grade) => (
                  <option key={grade.code} value={grade.code}>
                    {translateCarName(grade.name, language)}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Row 2: Year Range, Mileage Range */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            {/* Year Range */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.yearRange}
              </label>
              <div className="flex items-center gap-2">
                <select
                  value={yearFrom}
                  onChange={(e) => setYearFrom(e.target.value)}
                  disabled={isSubmitting}
                  className="flex-1 border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
                >
                  <option value="">{t.yearFrom}</option>
                  {yearOptions.map((year) => (
                    <option key={year} value={year}>{year}</option>
                  ))}
                </select>
                <span className="text-gray-400">~</span>
                <select
                  value={yearTo}
                  onChange={(e) => setYearTo(e.target.value)}
                  disabled={isSubmitting}
                  className="flex-1 border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
                >
                  <option value="">{t.yearTo}</option>
                  {yearOptions.map((year) => (
                    <option key={year} value={year}>{year}</option>
                  ))}
                </select>
              </div>
            </div>

            {/* Mileage Range */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.mileageRange} ({t.tenThousandKm})
              </label>
              <div className="flex items-center gap-2">
                <select
                  value={mileageMin}
                  onChange={(e) => setMileageMin(e.target.value)}
                  disabled={isSubmitting}
                  className="flex-1 border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
                >
                  <option value="">{t.mileageFrom}</option>
                  {mileageOptions.map((m) => (
                    <option key={m} value={m}>{m}</option>
                  ))}
                </select>
                <span className="text-gray-400">~</span>
                <select
                  value={mileageMax}
                  onChange={(e) => setMileageMax(e.target.value)}
                  disabled={isSubmitting}
                  className="flex-1 border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
                >
                  <option value="">{t.mileageTo}</option>
                  {mileageOptions.map((m) => (
                    <option key={m} value={m}>{m}</option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          {/* Row 3: Fuel Type, Displacement */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            {/* Fuel Type */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.fuel}
              </label>
              <select
                value={selectedFuel}
                onChange={(e) => setSelectedFuel(e.target.value)}
                disabled={isSubmitting}
                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
              >
                <option value="">{t.allFuelTypes}</option>
                {fuelOptions.map((fuel) => (
                  <option key={fuel.value} value={fuel.value}>
                    {fuel.label[language as keyof typeof fuel.label] || fuel.label.en}
                  </option>
                ))}
              </select>
            </div>

            {/* Displacement */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.displacement} (cc)
              </label>
              <div className="flex items-center gap-2">
                <select
                  value={displacementMin}
                  onChange={(e) => setDisplacementMin(e.target.value)}
                  disabled={isSubmitting}
                  className="flex-1 border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
                >
                  <option value="">{language === 'ko' ? '최소' : 'Min'}</option>
                  {displacementOptions.map((d) => (
                    <option key={d} value={d}>{d.toLocaleString()}</option>
                  ))}
                </select>
                <span className="text-gray-400">~</span>
                <select
                  value={displacementMax}
                  onChange={(e) => setDisplacementMax(e.target.value)}
                  disabled={isSubmitting}
                  className="flex-1 border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
                >
                  <option value="">{language === 'ko' ? '최대' : 'Max'}</option>
                  {displacementOptions.map((d) => (
                    <option key={d} value={d}>{d.toLocaleString()}</option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          {/* Validation Error */}
          {validationError && (
            <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-md">
              <p className="text-red-600 text-sm">{validationError}</p>
            </div>
          )}

          {/* Required Fields Notice */}
          <div className="mt-4 text-sm text-gray-500">
            <span className="text-red-500">*</span> {language === 'ko' ? '필수 입력 항목입니다.' : 'Required fields'}
          </div>

          {/* CC Cost Notice */}
          <div className="mt-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <svg className="w-5 h-5 text-blue-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span className="text-blue-700 font-medium">{t.requestCost}</span>
              </div>
              <div className="text-right">
                <span className="text-sm text-gray-600">{t.ccBalance}: </span>
                <span className={`font-bold ${ccBalance >= QUOTE_REQUEST_COST ? 'text-green-600' : 'text-red-600'}`}>
                  {ccBalance} CC
                </span>
              </div>
            </div>
            {ccBalance < QUOTE_REQUEST_COST && (
              <div className="mt-2 flex items-center justify-between">
                <p className="text-sm text-red-600">{t.insufficientCC}</p>
                <Link href="/cc" className="text-sm text-blue-600 hover:underline font-medium">
                  {t.charge} →
                </Link>
              </div>
            )}
          </div>

          {/* Submit Button */}
          <div className="mt-6">
            <button
              type="submit"
              disabled={isSubmitting || !isFormValid()}
              className="w-full bg-primary-600 text-white py-3 rounded-md hover:bg-primary-700 transition disabled:opacity-50 disabled:cursor-not-allowed font-medium flex items-center justify-center"
            >
              {isSubmitting ? (
                <>
                  <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  {t.submitting}
                </>
              ) : (
                <>
                  {t.submitRequest} ({QUOTE_REQUEST_COST} CC)
                </>
              )}
            </button>
          </div>
        </form>

        {/* Info Cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {/* Step 1 */}
          <div className="bg-white rounded-lg shadow-md p-6 text-center">
            <div className="w-12 h-12 bg-primary-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <span className="text-primary-600 font-bold text-lg">1</span>
            </div>
            <h3 className="font-semibold text-gray-800 mb-2">{t.step1Title}</h3>
            <p className="text-gray-600 text-sm">{t.step1Desc}</p>
          </div>

          {/* Step 2 */}
          <div className="bg-white rounded-lg shadow-md p-6 text-center">
            <div className="w-12 h-12 bg-primary-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <span className="text-primary-600 font-bold text-lg">2</span>
            </div>
            <h3 className="font-semibold text-gray-800 mb-2">{t.step2Title}</h3>
            <p className="text-gray-600 text-sm">{t.step2Desc}</p>
          </div>

          {/* Step 3 */}
          <div className="bg-white rounded-lg shadow-md p-6 text-center">
            <div className="w-12 h-12 bg-primary-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <span className="text-primary-600 font-bold text-lg">3</span>
            </div>
            <h3 className="font-semibold text-gray-800 mb-2">{t.step3Title}</h3>
            <p className="text-gray-600 text-sm">{t.step3Desc}</p>
          </div>
        </div>
      </div>

      {/* CC Confirmation Modal */}
      {showConfirmModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 overflow-hidden">
            {/* Modal Header */}
            <div className="bg-primary-600 text-white px-6 py-4">
              <h3 className="text-lg font-bold flex items-center">
                <svg className="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                {t.confirmPayment || 'Confirm Payment'}
              </h3>
            </div>

            {/* Modal Body */}
            <div className="px-6 py-6">
              {ccBalance >= QUOTE_REQUEST_COST ? (
                <>
                  {/* Sufficient CC */}
                  <div className="text-center mb-6">
                    <div className="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4">
                      <span className="text-3xl font-bold text-yellow-600">CC</span>
                    </div>
                    <p className="text-gray-700 text-lg mb-2">
                      {t.requestRequiresCC || 'This request requires'}
                    </p>
                    <p className="text-3xl font-bold text-primary-600">{QUOTE_REQUEST_COST} CC</p>
                  </div>

                  {/* Balance Info */}
                  <div className="bg-gray-50 rounded-lg p-4 mb-6">
                    <div className="flex justify-between items-center">
                      <span className="text-gray-600">{t.currentBalance || 'Current Balance'}</span>
                      <span className="font-bold text-green-600">{ccBalance} CC</span>
                    </div>
                    <div className="flex justify-between items-center mt-2 pt-2 border-t">
                      <span className="text-gray-600">{t.afterPayment || 'After Payment'}</span>
                      <span className="font-bold text-gray-800">{ccBalance - QUOTE_REQUEST_COST} CC</span>
                    </div>
                  </div>

                  {/* Action Buttons */}
                  <div className="flex gap-3">
                    <button
                      type="button"
                      onClick={() => setShowConfirmModal(false)}
                      className="flex-1 px-4 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition font-medium"
                    >
                      {t.cancel}
                    </button>
                    <button
                      type="button"
                      onClick={handleConfirmSubmit}
                      className="flex-1 px-4 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition font-medium"
                    >
                      {t.confirmAndPay || 'Confirm & Pay'}
                    </button>
                  </div>
                </>
              ) : (
                <>
                  {/* Insufficient CC */}
                  <div className="text-center mb-6">
                    <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                      <svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                      </svg>
                    </div>
                    <p className="text-gray-700 text-lg mb-2">{t.insufficientCC}</p>
                    <p className="text-gray-500 text-sm">
                      {t.needMoreCC || 'You need'} <span className="font-bold text-red-600">{QUOTE_REQUEST_COST - ccBalance} CC</span> {t.more || 'more'}
                    </p>
                  </div>

                  {/* Balance Info */}
                  <div className="bg-red-50 rounded-lg p-4 mb-6">
                    <div className="flex justify-between items-center">
                      <span className="text-gray-600">{t.required || 'Required'}</span>
                      <span className="font-bold text-gray-800">{QUOTE_REQUEST_COST} CC</span>
                    </div>
                    <div className="flex justify-between items-center mt-2 pt-2 border-t border-red-200">
                      <span className="text-gray-600">{t.currentBalance || 'Current Balance'}</span>
                      <span className="font-bold text-red-600">{ccBalance} CC</span>
                    </div>
                  </div>

                  {/* Action Buttons */}
                  <div className="flex gap-3">
                    <button
                      type="button"
                      onClick={() => setShowConfirmModal(false)}
                      className="flex-1 px-4 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition font-medium"
                    >
                      {t.cancel}
                    </button>
                    <button
                      type="button"
                      onClick={() => router.push('/cc')}
                      className="flex-1 px-4 py-3 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition font-medium"
                    >
                      {t.chargeCC || 'Charge CC'}
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </SidebarLayout>
  );
}
