'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { heroBannersApi, adminPdfApi } from '@/lib/api';
import { HeroBannerSettings } from '@/types';

interface BannerFormData {
  title_ko: string;
  title_en: string;
  title_mn: string;
  subtitle_ko: string;
  subtitle_en: string;
  subtitle_mn: string;
  image_url: string;
  link_url: string;
  is_active: boolean;
  display_order: number;
  car_id?: number | null;  // 연결된 차량 ID (샘플 차량용)
}

const defaultFormData: BannerFormData = {
  title_ko: '',
  title_en: '',
  title_mn: '',
  subtitle_ko: '',
  subtitle_en: '',
  subtitle_mn: '',
  image_url: '',
  link_url: '',
  is_active: true,
  display_order: 0,
  car_id: null,
};

// 이미지 URL 변환 (로컬 경로는 백엔드 URL 추가)
const getImageUrl = (url: string | undefined): string => {
  if (!url) return '';
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  return `http://localhost:8000${url}`;
};

export default function HeroBannersPage() {
  const [banners, setBanners] = useState<any[]>([]);
  const [settings, setSettings] = useState<HeroBannerSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [formData, setFormData] = useState<BannerFormData>(defaultFormData);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [retryingPdfs, setRetryingPdfs] = useState(false);
  const [pdfStatus, setPdfStatus] = useState<Record<number, boolean>>({});

  // PDF 재시도 함수
  const handleRetryFailedPdfs = async () => {
    if (!confirm('PDF가 없는 모든 차량에 대해 PDF 생성을 재시도합니다. 계속하시겠습니까?')) {
      return;
    }

    setRetryingPdfs(true);
    try {
      const result = await adminPdfApi.retryAllFailed();
      if (result.total === 0) {
        alert('PDF가 없는 차량이 없습니다.');
      } else {
        alert(`PDF 재시도 완료!\n\n총: ${result.total}개\n성공: ${result.success}개\n실패: ${result.failed}개`);
        // Reload data to update PDF status
        await loadData();
      }
    } catch (error: any) {
      console.error('PDF retry failed:', error);
      alert('PDF 재시도 중 오류가 발생했습니다: ' + (error.response?.data?.detail || error.message));
    } finally {
      setRetryingPdfs(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      const [bannersData, settingsData] = await Promise.all([
        heroBannersApi.adminGetList(),
        heroBannersApi.getSettings(),
      ]);
      setBanners(bannersData);
      setSettings(settingsData);

      // Fetch PDF status for all banner cars
      const carIds = bannersData
        .filter((b: any) => b.car_id)
        .map((b: any) => b.car_id);
      if (carIds.length > 0) {
        try {
          const response = await fetch('http://localhost:8000/api/carmodoo/pdf-status', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(carIds),
          });
          if (response.ok) {
            const status = await response.json();
            setPdfStatus(status);
          }
        } catch (err) {
          console.error('Failed to fetch PDF status:', err);
        }
      }
    } catch (error) {
      console.error('Failed to load data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingId(null);
    setFormData(defaultFormData);
    setShowModal(true);
  };

  const handleEdit = async (id: number) => {
    try {
      const banner = await heroBannersApi.adminGetById(id);
      setFormData({
        title_ko: banner.title_ko || '',
        title_en: banner.title_en || '',
        title_mn: banner.title_mn || '',
        subtitle_ko: banner.subtitle_ko || '',
        subtitle_en: banner.subtitle_en || '',
        subtitle_mn: banner.subtitle_mn || '',
        image_url: banner.image_url || '',
        link_url: banner.link_url || '',
        is_active: banner.is_active ?? true,
        display_order: banner.display_order || 0,
      });
      setEditingId(id);
      setShowModal(true);
    } catch (error) {
      console.error('Failed to load banner:', error);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Are you sure you want to delete this banner?')) return;

    try {
      await heroBannersApi.adminDelete(id);
      await loadData();
    } catch (error) {
      console.error('Failed to delete banner:', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      if (editingId) {
        await heroBannersApi.adminUpdate(editingId, formData);
      } else {
        await heroBannersApi.adminCreate(formData);
      }
      setShowModal(false);
      await loadData();
    } catch (error) {
      console.error('Failed to save banner:', error);
    }
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      const result = await heroBannersApi.adminUploadImage(file);
      setFormData({ ...formData, image_url: result.image_url });
    } catch (error) {
      console.error('Failed to upload image:', error);
      alert('Failed to upload image');
    } finally {
      setUploading(false);
    }
  };

  const handleSettingsUpdate = async (newSettings: Partial<HeroBannerSettings>) => {
    try {
      const updated = await heroBannersApi.adminUpdateSettings(newSettings);
      setSettings(updated);
    } catch (error) {
      console.error('Failed to update settings:', error);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-800">Hero Banners</h1>
        <div className="flex gap-2">
          <button
            onClick={handleRetryFailedPdfs}
            disabled={retryingPdfs}
            className="bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-600 transition-colors flex items-center gap-2 disabled:opacity-50"
            title="PDF가 없는 차량들의 PDF를 재생성합니다"
          >
            {retryingPdfs ? (
              <>
                <span className="animate-spin">⏳</span>
                <span>PDF 생성중...</span>
              </>
            ) : (
              <>
                <span>📄</span>
                <span>PDF 재시도</span>
              </>
            )}
          </button>
          <Link
            href="/admin/cars"
            className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2"
          >
            <span>🚗</span>
            <span>Add from Cars Page</span>
          </Link>
          <button
            onClick={handleCreate}
            className="bg-primary-600 text-white px-4 py-2 rounded-lg hover:bg-primary-700 transition-colors flex items-center gap-2"
          >
            <span>+</span>
            <span>Add Banner</span>
          </button>
        </div>
      </div>

      {/* Slider Settings */}
      {settings && (
        <div className="bg-white rounded-xl shadow-sm p-6 mb-6">
          <h2 className="text-lg font-semibold text-gray-800 mb-4">Slider Settings</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Slide Interval (ms)
              </label>
              <input
                type="number"
                value={settings.slide_interval}
                onChange={(e) => handleSettingsUpdate({ slide_interval: parseInt(e.target.value) })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Image Width (px)
              </label>
              <input
                type="number"
                value={settings.image_width}
                onChange={(e) => handleSettingsUpdate({ image_width: parseInt(e.target.value) })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Image Height (px)
              </label>
              <input
                type="number"
                value={settings.image_height}
                onChange={(e) => handleSettingsUpdate({ image_height: parseInt(e.target.value) })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
              />
            </div>
          </div>
        </div>
      )}

      {/* Banners Table */}
      <div className="bg-white rounded-xl shadow-sm overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Image</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Title</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Order</th>
              <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">PDF</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
              <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {banners.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-6 py-12 text-center text-gray-500">
                  No banners yet. Click "Add Banner" or "Add from Car Search" to create one.
                </td>
              </tr>
            ) : (
              banners.map((banner) => (
                <tr key={banner.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4">
                    <div className="w-24 h-14 relative rounded overflow-hidden bg-gray-200">
                      {banner.image_url ? (
                        <img
                          src={getImageUrl(banner.image_url)}
                          alt={banner.title_en || 'Banner'}
                          className="w-full h-full object-cover"
                        />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center text-gray-400 text-xs">
                          No image
                        </div>
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <p className="font-medium text-gray-800">{banner.title_en || banner.title_ko || 'Untitled'}</p>
                    {banner.subtitle_en && <p className="text-sm text-gray-500">{banner.subtitle_en}</p>}
                  </td>
                  <td className="px-6 py-4 text-gray-600">{banner.display_order}</td>
                  <td className="px-6 py-4 text-center">
                    {banner.car_id ? (
                      pdfStatus[banner.car_id] ? (
                        <span className="px-2 py-1 text-xs rounded-full bg-green-100 text-green-700" title="PDF Available">
                          ✓ PDF
                        </span>
                      ) : (
                        <span className="px-2 py-1 text-xs rounded-full bg-red-100 text-red-700" title="PDF Not Available">
                          ✗ PDF
                        </span>
                      )
                    ) : (
                      <span className="text-gray-400">-</span>
                    )}
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${banner.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}`}>
                      {banner.is_active ? 'Active' : 'Inactive'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-right space-x-2">
                    <button onClick={() => handleEdit(banner.id)} className="text-primary-600 hover:text-primary-800">Edit</button>
                    <button onClick={() => handleDelete(banner.id)} className="text-red-600 hover:text-red-800">Delete</button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Banner Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-gray-200">
              <h2 className="text-xl font-bold text-gray-800">
                {editingId ? 'Edit Banner' : 'Add New Banner'}
              </h2>
            </div>

            <form onSubmit={handleSubmit} className="p-6 space-y-6">
              {/* Image Upload */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Banner Image (500x300 recommended)
                </label>
                <div className="flex items-start gap-4">
                  <div className="w-40 h-24 bg-gray-200 rounded-lg overflow-hidden flex-shrink-0">
                    {formData.image_url ? (
                      <img
                        src={getImageUrl(formData.image_url)}
                        alt="Preview"
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-gray-400">
                        No image
                      </div>
                    )}
                  </div>
                  <div className="flex-1">
                    <input
                      type="file"
                      ref={fileInputRef}
                      onChange={handleImageUpload}
                      accept="image/*"
                      className="hidden"
                    />
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      disabled={uploading}
                      className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                    >
                      {uploading ? 'Uploading...' : 'Upload Image'}
                    </button>
                    <p className="text-sm text-gray-500 mt-2">Or enter URL directly:</p>
                    <input
                      type="text"
                      value={formData.image_url}
                      onChange={(e) => setFormData({ ...formData, image_url: e.target.value })}
                      placeholder="https://..."
                      className="mt-1 w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                    />
                  </div>
                </div>
              </div>

              {/* Titles */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Title (Korean)</label>
                  <input
                    type="text"
                    value={formData.title_ko}
                    onChange={(e) => setFormData({ ...formData, title_ko: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Title (English)</label>
                  <input
                    type="text"
                    value={formData.title_en}
                    onChange={(e) => setFormData({ ...formData, title_en: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Title (Mongolian)</label>
                  <input
                    type="text"
                    value={formData.title_mn}
                    onChange={(e) => setFormData({ ...formData, title_mn: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                  />
                </div>
              </div>

              {/* Subtitles */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Subtitle (Korean)</label>
                  <input
                    type="text"
                    value={formData.subtitle_ko}
                    onChange={(e) => setFormData({ ...formData, subtitle_ko: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Subtitle (English)</label>
                  <input
                    type="text"
                    value={formData.subtitle_en}
                    onChange={(e) => setFormData({ ...formData, subtitle_en: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Subtitle (Mongolian)</label>
                  <input
                    type="text"
                    value={formData.subtitle_mn}
                    onChange={(e) => setFormData({ ...formData, subtitle_mn: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                  />
                </div>
              </div>

              {/* Link URL */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Link URL (optional)</label>
                <input
                  type="text"
                  value={formData.link_url}
                  onChange={(e) => setFormData({ ...formData, link_url: e.target.value })}
                  placeholder="/cars or https://..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                />
              </div>

              {/* Order & Status */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Display Order</label>
                  <input
                    type="number"
                    value={formData.display_order}
                    onChange={(e) => setFormData({ ...formData, display_order: parseInt(e.target.value) })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
                  <label className="flex items-center gap-2 mt-2">
                    <input
                      type="checkbox"
                      checked={formData.is_active}
                      onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                      className="w-5 h-5 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                    />
                    <span className="text-gray-700">Active</span>
                  </label>
                </div>
              </div>

              {/* Actions */}
              <div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
                >
                  {editingId ? 'Update' : 'Create'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
