'use client';

import { useState, useEffect } from 'react';
import { vehicleRequestsApi, PurchasedVehicle } from '@/lib/api';
import { useExchangeRateStore } from '@/lib/exchangeRateStore';

const SHIPPING_STEPS = [
  { step: 1, label: 'Purchased', labelKo: '구매 완료' },
  { step: 2, label: 'Incheon Port', labelKo: '인천항' },
  { step: 3, label: 'Tianjin Port', labelKo: '텐진항 (중국)' },
  { step: 4, label: 'Zamyn-Uud', labelKo: '자먼우드 (몽골)' },
  { step: 5, label: 'Ulaanbaatar', labelKo: '울란바토르' },
  { step: 6, label: 'Customs', labelKo: '통관' },
  { step: 7, label: 'Delivered', labelKo: '배송 완료' },
];

export default function AdminPurchasedPage() {
  const [vehicles, setVehicles] = useState<PurchasedVehicle[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedVehicle, setSelectedVehicle] = useState<PurchasedVehicle | null>(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);

  // Edit form state
  const [editStatus, setEditStatus] = useState<number>(1);
  const [editLocation, setEditLocation] = useState<string>('');
  const [editArrival, setEditArrival] = useState<string>('');

  // Create form state
  const [createUserId, setCreateUserId] = useState<string>('');
  const [createCarName, setCreateCarName] = useState<string>('');
  const [createCarImage, setCreateCarImage] = useState<string>('');
  const [createVehiclePrice, setCreateVehiclePrice] = useState<string>('');
  const [createDomesticCost, setCreateDomesticCost] = useState<string>('1207500'); // 1,150,000 + 5%
  const [createShippingCost, setCreateShippingCost] = useState<string>('1000');
  const [createCarType, setCreateCarType] = useState<string>('small');

  // Load vehicles
  useEffect(() => {
    loadVehicles();
  }, []);

  const loadVehicles = async () => {
    try {
      setIsLoading(true);
      const data = await vehicleRequestsApi.adminGetAllPurchased();
      setVehicles(data);
    } catch (error) {
      console.error('Failed to load vehicles:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // Open edit modal
  const openEditModal = (vehicle: PurchasedVehicle) => {
    setSelectedVehicle(vehicle);
    setEditStatus(vehicle.shipping_status);
    setEditLocation(vehicle.current_location || '');
    setEditArrival(vehicle.estimated_arrival ? vehicle.estimated_arrival.split('T')[0] : '');
    setShowEditModal(true);
  };

  // Update shipping status
  const updateShippingStatus = async () => {
    if (!selectedVehicle) return;

    try {
      await vehicleRequestsApi.adminUpdateShippingStatus(selectedVehicle.id, {
        shipping_status: editStatus,
        current_location: editLocation || undefined,
        estimated_arrival: editArrival || undefined,
      });

      setShowEditModal(false);
      loadVehicles();
    } catch (error) {
      console.error('Failed to update status:', error);
    }
  };

  // Create purchased vehicle
  const createPurchasedVehicle = async () => {
    if (!createUserId || !createCarName || !createVehiclePrice) {
      alert('Please fill in all required fields');
      return;
    }

    try {
      const vehiclePrice = parseInt(createVehiclePrice) * 10000;
      const domesticCost = parseInt(createDomesticCost);
      const shippingCostUsd = parseInt(createShippingCost);
      const usdToKrw = useExchangeRateStore.getState().rates.USD?.rate || 1483;
      const shippingCostKrw = shippingCostUsd * usdToKrw;

      // Calculate total with 5% Mongolian margin
      const subtotal = vehiclePrice + domesticCost + shippingCostKrw;
      const mongolianMargin = subtotal * 0.05;
      const totalCost = Math.round(subtotal + mongolianMargin);

      await vehicleRequestsApi.adminCreatePurchased(parseInt(createUserId), {
        car_name: createCarName,
        car_image: createCarImage || undefined,
        vehicle_price_krw: vehiclePrice,
        domestic_cost_krw: domesticCost,
        shipping_cost_usd: shippingCostUsd,
        total_cost_krw: totalCost,
        car_type: createCarType,
      });

      setShowCreateModal(false);
      resetCreateForm();
      loadVehicles();
    } catch (error) {
      console.error('Failed to create vehicle:', error);
    }
  };

  const resetCreateForm = () => {
    setCreateUserId('');
    setCreateCarName('');
    setCreateCarImage('');
    setCreateVehiclePrice('');
    setCreateDomesticCost('1207500');
    setCreateShippingCost('1000');
    setCreateCarType('small');
  };

  // Format date
  const formatDate = (dateString: string | null | undefined) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleDateString('ko-KR', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    });
  };

  // Format price
  const formatPrice = (price: number | null | undefined) => {
    if (!price) return '-';
    return `₩${price.toLocaleString()}`;
  };

  // Get status badge
  const getStatusBadge = (status: number) => {
    const step = SHIPPING_STEPS.find(s => s.step === status);
    const colors = [
      '',
      'bg-yellow-100 text-yellow-800',   // 1: Purchased
      'bg-blue-100 text-blue-800',       // 2: Incheon
      'bg-cyan-100 text-cyan-800',       // 3: Tianjin
      'bg-indigo-100 text-indigo-800',   // 4: Zamyn-Uud
      'bg-purple-100 text-purple-800',   // 5: Ulaanbaatar
      'bg-orange-100 text-orange-800',   // 6: Customs
      'bg-green-100 text-green-800',     // 7: Delivered
    ];
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${colors[status] || 'bg-gray-100 text-gray-800'}`}>
        {step?.label || `Step ${status}`}
      </span>
    );
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-800">Purchased Vehicles</h1>
        <button
          onClick={() => setShowCreateModal(true)}
          className="bg-primary-600 text-white px-4 py-2 rounded-lg hover:bg-primary-700"
        >
          + Add Purchased Vehicle
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-7 gap-3">
        {SHIPPING_STEPS.map((step) => {
          const count = vehicles.filter(v => v.shipping_status === step.step).length;
          return (
            <div key={step.step} className="bg-white rounded-lg shadow p-4 text-center">
              <div className="text-2xl font-bold text-gray-800">{count}</div>
              <div className="text-sm text-gray-500">{step.label}</div>
            </div>
          );
        })}
      </div>

      {/* Vehicles Table */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        {isLoading ? (
          <div className="p-8 text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600 mx-auto"></div>
          </div>
        ) : vehicles.length === 0 ? (
          <div className="p-8 text-center text-gray-500">No purchased vehicles</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Vehicle</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">User ID</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Type</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Total Cost</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Location</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Est. Arrival</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {vehicles.map((vehicle) => (
                  <tr key={vehicle.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3 text-sm text-gray-500">{vehicle.id}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        {vehicle.car_image && (
                          <img src={vehicle.car_image} alt="" className="w-12 h-9 object-cover rounded" />
                        )}
                        <span className="text-sm font-medium text-gray-800 max-w-[150px] truncate">
                          {vehicle.car_name}
                        </span>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500">{vehicle.user_id}</td>
                    <td className="px-4 py-3 text-sm text-gray-500 capitalize">{vehicle.car_type}</td>
                    <td className="px-4 py-3 text-sm font-medium text-gray-800">
                      {formatPrice(vehicle.total_cost_krw)}
                    </td>
                    <td className="px-4 py-3">{getStatusBadge(vehicle.shipping_status)}</td>
                    <td className="px-4 py-3 text-sm text-gray-500 max-w-[100px] truncate">
                      {vehicle.current_location || '-'}
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500">
                      {formatDate(vehicle.estimated_arrival)}
                    </td>
                    <td className="px-4 py-3">
                      <button
                        onClick={() => openEditModal(vehicle)}
                        className="text-primary-600 hover:text-primary-800 text-sm font-medium"
                      >
                        Update Status
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Edit Modal */}
      {showEditModal && selectedVehicle && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg max-w-md w-full">
            <div className="p-4 border-b flex items-center justify-between">
              <h3 className="font-semibold text-gray-800">Update Shipping Status</h3>
              <button onClick={() => setShowEditModal(false)} className="text-gray-500 hover:text-gray-700">
                &times;
              </button>
            </div>

            <div className="p-4 space-y-4">
              <div className="bg-gray-50 rounded p-3">
                <p className="font-medium text-sm">{selectedVehicle.car_name}</p>
                <p className="text-xs text-gray-500">User ID: {selectedVehicle.user_id}</p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Shipping Status
                </label>
                <div className="grid grid-cols-7 gap-1">
                  {SHIPPING_STEPS.map((step) => (
                    <button
                      key={step.step}
                      onClick={() => setEditStatus(step.step)}
                      className={`p-2 rounded text-xs text-center ${
                        editStatus === step.step
                          ? 'bg-primary-600 text-white'
                          : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                      }`}
                    >
                      {step.step}
                    </button>
                  ))}
                </div>
                <p className="mt-2 text-sm text-gray-600">
                  Selected: {SHIPPING_STEPS.find(s => s.step === editStatus)?.label}
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Current Location
                </label>
                <input
                  type="text"
                  value={editLocation}
                  onChange={(e) => setEditLocation(e.target.value)}
                  placeholder="e.g., Incheon Port, On Ship, Ulaanbaatar"
                  className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Estimated Arrival Date
                </label>
                <input
                  type="date"
                  value={editArrival}
                  onChange={(e) => setEditArrival(e.target.value)}
                  className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                />
              </div>

              <div className="flex gap-2 pt-4">
                <button
                  onClick={() => setShowEditModal(false)}
                  className="flex-1 px-4 py-2 border border-gray-300 rounded text-gray-700 hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={updateShippingStatus}
                  className="flex-1 px-4 py-2 bg-primary-600 text-white rounded hover:bg-primary-700"
                >
                  Update
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Create Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg max-w-md w-full max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex items-center justify-between">
              <h3 className="font-semibold text-gray-800">Add Purchased Vehicle</h3>
              <button onClick={() => { setShowCreateModal(false); resetCreateForm(); }} className="text-gray-500 hover:text-gray-700">
                &times;
              </button>
            </div>

            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  User ID <span className="text-red-500">*</span>
                </label>
                <input
                  type="number"
                  value={createUserId}
                  onChange={(e) => setCreateUserId(e.target.value)}
                  className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Car Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={createCarName}
                  onChange={(e) => setCreateCarName(e.target.value)}
                  placeholder="e.g., 2022 Hyundai Sonata"
                  className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Car Image URL
                </label>
                <input
                  type="text"
                  value={createCarImage}
                  onChange={(e) => setCreateCarImage(e.target.value)}
                  placeholder="https://..."
                  className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Vehicle Price (만원) <span className="text-red-500">*</span>
                </label>
                <input
                  type="number"
                  value={createVehiclePrice}
                  onChange={(e) => setCreateVehiclePrice(e.target.value)}
                  placeholder="2000"
                  className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                />
                {createVehiclePrice && (
                  <p className="text-xs text-gray-500 mt-1">
                    = ₩{(parseInt(createVehiclePrice) * 10000).toLocaleString()}
                  </p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Domestic Cost (원)
                </label>
                <input
                  type="number"
                  value={createDomesticCost}
                  onChange={(e) => setCreateDomesticCost(e.target.value)}
                  className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                />
                <p className="text-xs text-gray-500 mt-1">
                  Default: ₩1,150,000 + 5% margin = ₩1,207,500
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Car Type
                </label>
                <div className="grid grid-cols-2 gap-2">
                  <button
                    onClick={() => { setCreateCarType('small'); setCreateShippingCost('1000'); }}
                    className={`p-3 rounded border-2 ${
                      createCarType === 'small'
                        ? 'border-primary-500 bg-primary-50'
                        : 'border-gray-200'
                    }`}
                  >
                    <div className="font-medium">Small Car</div>
                    <div className="text-sm text-gray-500">$1,000</div>
                  </button>
                  <button
                    onClick={() => { setCreateCarType('compact'); setCreateShippingCost('800'); }}
                    className={`p-3 rounded border-2 ${
                      createCarType === 'compact'
                        ? 'border-primary-500 bg-primary-50'
                        : 'border-gray-200'
                    }`}
                  >
                    <div className="font-medium">Compact Car</div>
                    <div className="text-sm text-gray-500">$800</div>
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Shipping Cost (USD)
                </label>
                <input
                  type="number"
                  value={createShippingCost}
                  onChange={(e) => setCreateShippingCost(e.target.value)}
                  className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                />
              </div>

              {/* Cost Preview */}
              {createVehiclePrice && (
                <div className="bg-gray-50 rounded p-3 text-sm">
                  <h4 className="font-medium mb-2">Cost Preview</h4>
                  <div className="space-y-1">
                    <div className="flex justify-between">
                      <span>Vehicle:</span>
                      <span>₩{(parseInt(createVehiclePrice || '0') * 10000).toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>Domestic:</span>
                      <span>₩{parseInt(createDomesticCost || '0').toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>Shipping:</span>
                      <span>${parseInt(createShippingCost || '0').toLocaleString()} (≈₩{(parseInt(createShippingCost || '0') * (useExchangeRateStore.getState().rates.USD?.rate || 1483)).toLocaleString()})</span>
                    </div>
                    <div className="flex justify-between border-t pt-1 font-medium">
                      <span>Total (+ 5% margin):</span>
                      <span>
                        ₩{(() => {
                          const vp = parseInt(createVehiclePrice || '0') * 10000;
                          const dc = parseInt(createDomesticCost || '0');
                          const usdRate = useExchangeRateStore.getState().rates.USD?.rate || 1483;
                          const sc = parseInt(createShippingCost || '0') * usdRate;
                          const subtotal = vp + dc + sc;
                          const total = Math.round(subtotal * 1.05);
                          return total.toLocaleString();
                        })()}
                      </span>
                    </div>
                  </div>
                </div>
              )}

              <div className="flex gap-2 pt-4">
                <button
                  onClick={() => { setShowCreateModal(false); resetCreateForm(); }}
                  className="flex-1 px-4 py-2 border border-gray-300 rounded text-gray-700 hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={createPurchasedVehicle}
                  className="flex-1 px-4 py-2 bg-primary-600 text-white rounded hover:bg-primary-700"
                >
                  Create
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
