'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 } from '@/lib/api';
import SidebarLayout from '@/components/SidebarLayout';

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

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

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

  // Load requests
  useEffect(() => {
    const loadRequests = async () => {
      if (!user) return;

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

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

  // Format date
  const formatDate = (dateString: string) => {
    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',
    });
  };

  // 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 Requests */}
        {!isLoading && !error && requests.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);

                        return (
                          <div key={vehicle.id} className="bg-white rounded-lg shadow-sm overflow-hidden border">
                            {/* Vehicle Image */}
                            <div className="relative h-40 bg-gray-200">
                              {carData?.main_image ? (
                                <Image
                                  src={carData.main_image}
                                  alt={carData.car_name || 'Vehicle'}
                                  fill
                                  className="object-cover"
                                  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>
                              )}
                            </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>
                          </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>
        )}
      </div>
    </SidebarLayout>
  );
}
