'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, CarmodooMaker, CarmodooModel } from '@/lib/api';

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>('');

  // 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);

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

  // 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
  const handleSubmit = async (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('');
    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,
      });

      setSubmitSuccess(true);
    } catch (error) {
      console.error('Failed to submit request:', error);
      setValidationError(language === 'ko' ? '요청 제출에 실패했습니다. 다시 시도해주세요.' : 'Failed to submit request. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

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

  // 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];

  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=/request"
            className="bg-primary-600 text-white px-6 py-3 rounded-lg hover:bg-primary-700 transition"
          >
            {t.login}
          </Link>
        </div>
      </div>
    );
  }

  // Success screen
  if (submitSuccess) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="container mx-auto px-4">
          <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>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4">
        {/* 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="max-w-4xl mx-auto 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="max-w-4xl mx-auto 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>

          {/* 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>

          {/* 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
              )}
            </button>
          </div>
        </form>

        {/* Info Cards */}
        <div className="max-w-4xl mx-auto 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>
    </div>
  );
}
