'use client';

import { useState, useEffect, useRef } from 'react';
import { 
  Plus,
  Loader2,
  Edit,
  Trash2,
  Save,
  X,
  Eye,
  EyeOff,
  Image as ImageIcon,
  Upload,
  Trash,
  Link as LinkIcon,
  ExternalLink,
  CheckCircle
} from 'lucide-react';
import Link from 'next/link';

interface Case {
  id: string;
  title: string;
  description: string | null;
  images: string[];
  category: string | null;
  sort_order: number;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

const categories = ['铁路运输', '公路运输', '清关服务', '仓储服务', '其他'];

export default function AdminCasesPage() {
  const [cases, setCases] = useState<Case[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingCase, setEditingCase] = useState<Case | null>(null);
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    category: '',
    images: [] as string[],
    sort_order: 0,
    is_active: true
  });
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');
  const [tableExists, setTableExists] = useState<boolean | null>(null);
  const [initializing, setInitializing] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 获取案例列表
  const fetchCases = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('/api/admin/cases');
      const data = await response.json();
      if (response.ok) {
        setCases(data.cases || []);
        setTableExists(true);
      } else if (data.code === 'PGRST205' || data.code === '42P01') {
        // 表不存在
        setTableExists(false);
        setCases([]);
      }
    } catch (error) {
      console.error('Error fetching cases:', error);
    } finally {
      setIsLoading(false);
    }
  };

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

  // 初始化数据库表
  const handleInitDatabase = async () => {
    if (!confirm('确定要初始化数据库吗？\n\n这将创建必要的表结构。')) return;

    setInitializing(true);
    try {
      const response = await fetch('/api/admin/init-content', {
        method: 'POST'
      });
      const data = await response.json();
      
      if (data.success) {
        alert('初始化成功！');
        fetchCases();
      } else if (data.sqlScript) {
        // 表不存在，需要手动执行SQL
        alert('数据库表不存在，请在Supabase控制台执行以下SQL脚本：\n\nsql/init-cases-faqs.sql\n\n执行完成后刷新此页面。');
      } else {
        alert(data.error || '初始化失败');
      }
    } catch (error) {
      console.error('Error initializing:', error);
      alert('初始化失败');
    } finally {
      setInitializing(false);
    }
  };

  // 打开新增模态框
  const openAddModal = () => {
    setEditingCase(null);
    setFormData({
      title: '',
      description: '',
      category: '',
      images: [],
      sort_order: 0,
      is_active: true
    });
    setShowModal(true);
  };

  // 打开编辑模态框
  const openEditModal = (caseItem: Case) => {
    setEditingCase(caseItem);
    setFormData({
      title: caseItem.title,
      description: caseItem.description || '',
      category: caseItem.category || '',
      images: caseItem.images || [],
      sort_order: caseItem.sort_order || 0,
      is_active: caseItem.is_active
    });
    setShowModal(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setShowModal(false);
    setEditingCase(null);
  };

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

    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', 'case');

      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData
      });

      const data = await response.json();
      if (response.ok && data.url) {
        setFormData(prev => ({
          ...prev,
          images: [...prev.images, data.url]
        }));
      } else {
        alert(data.error || '上传失败');
      }
    } catch (error) {
      console.error('Error uploading image:', error);
      alert('上传失败');
    } finally {
      setUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  // 通过URL添加图片
  const handleAddImageUrl = () => {
    if (!imageUrl.trim()) return;
    setFormData(prev => ({
      ...prev,
      images: [...prev.images, imageUrl.trim()]
    }));
    setImageUrl('');
  };

  // 删除图片
  const handleRemoveImage = (index: number) => {
    setFormData(prev => ({
      ...prev,
      images: prev.images.filter((_, i) => i !== index)
    }));
  };

  // 保存案例
  const handleSave = async () => {
    if (!formData.title.trim()) {
      alert('请输入标题');
      return;
    }
    if (formData.images.length === 0) {
      alert('请至少上传一张图片');
      return;
    }

    setSaving(true);
    try {
      const url = editingCase 
        ? `/api/admin/cases/${editingCase.id}`
        : '/api/admin/cases';
      const method = editingCase ? 'PUT' : 'POST';

      // 转换字段名为 camelCase
      const payload = {
        title: formData.title,
        description: formData.description || undefined,
        images: formData.images,
        category: formData.category || undefined,
        sortOrder: formData.sort_order,
        isActive: formData.is_active
      };

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      });

      const data = await response.json();
      if (response.ok) {
        closeModal();
        fetchCases();
      } else {
        alert(data.error || '保存失败');
      }
    } catch (error) {
      console.error('Error saving case:', error);
      alert('保存失败');
    } finally {
      setSaving(false);
    }
  };

  // 删除案例
  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这个案例吗？')) return;

    try {
      const response = await fetch(`/api/admin/cases/${id}`, {
        method: 'DELETE'
      });

      if (response.ok) {
        fetchCases();
      } else {
        const data = await response.json();
        alert(data.error || '删除失败');
      }
    } catch (error) {
      console.error('Error deleting case:', error);
      alert('删除失败');
    }
  };

  // 切换状态
  const toggleActive = async (caseItem: Case) => {
    try {
      const response = await fetch(`/api/admin/cases/${caseItem.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          ...caseItem,
          isActive: !caseItem.is_active
        })
      });

      if (response.ok) {
        fetchCases();
      }
    } catch (error) {
      console.error('Error toggling case:', error);
    }
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">案例管理</h1>
          <p className="text-gray-500 mt-1">管理网站案例展示内容</p>
        </div>
        <div className="flex items-center gap-3">
          <Link 
            href="/cases" 
            target="_blank"
            className="inline-flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-blue-600 bg-gray-100 rounded-lg transition-colors text-sm"
          >
            <ExternalLink className="w-4 h-4" />
            预览页面
          </Link>
          <button
            onClick={openAddModal}
            className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
          >
            <Plus className="w-4 h-4" />
            新增案例
          </button>
        </div>
      </div>

      {/* 案例列表 */}
      {isLoading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
        </div>
      ) : tableExists === false ? (
        <div className="bg-white rounded-2xl p-12 border border-gray-100 text-center">
          <ImageIcon className="w-12 h-12 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">数据库表未初始化</h3>
          <p className="text-gray-500 mb-6">请点击下方按钮初始化数据库表</p>
          <button
            onClick={handleInitDatabase}
            disabled={initializing}
            className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium disabled:opacity-50"
          >
            {initializing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <CheckCircle className="w-4 h-4" />
            )}
            初始化数据库
          </button>
          <p className="text-xs text-gray-400 mt-4">
            或者手动在Supabase控制台执行 <code className="bg-gray-100 px-1 rounded">sql/init-cases-faqs.sql</code>
          </p>
        </div>
      ) : cases.length === 0 ? (
        <div className="bg-white rounded-2xl p-12 border border-gray-100 text-center">
          <ImageIcon className="w-12 h-12 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">暂无案例</h3>
          <p className="text-gray-500 mb-6">点击"新增案例"添加第一个案例</p>
          <button
            onClick={openAddModal}
            className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm"
          >
            <Plus className="w-4 h-4" />
            新增案例
          </button>
        </div>
      ) : (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {cases.map((caseItem) => (
            <div 
              key={caseItem.id}
              className={`bg-white rounded-xl border overflow-hidden ${
                caseItem.is_active ? 'border-gray-100' : 'border-gray-200 opacity-60'
              }`}
            >
              {/* 图片 */}
              <div className="relative aspect-video bg-gray-100">
                {caseItem.images.length > 0 ? (
                  <img 
                    src={caseItem.images[0]} 
                    alt={caseItem.title}
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="flex items-center justify-center h-full">
                    <ImageIcon className="w-8 h-8 text-gray-300" />
                  </div>
                )}
                {caseItem.images.length > 1 && (
                  <div className="absolute bottom-2 right-2 bg-black/60 text-white text-xs px-2 py-1 rounded">
                    {caseItem.images.length} 张图片
                  </div>
                )}
                {!caseItem.is_active && (
                  <div className="absolute inset-0 bg-gray-900/50 flex items-center justify-center">
                    <span className="text-white text-sm font-medium">已隐藏</span>
                  </div>
                )}
              </div>

              {/* 内容 */}
              <div className="p-4">
                <div className="flex items-start justify-between gap-2 mb-2">
                  <h3 className="font-semibold text-gray-900 line-clamp-1">{caseItem.title}</h3>
                  {caseItem.category && (
                    <span className="text-xs px-2 py-0.5 bg-blue-50 text-blue-600 rounded-full whitespace-nowrap">
                      {caseItem.category}
                    </span>
                  )}
                </div>
                {caseItem.description && (
                  <p className="text-sm text-gray-500 line-clamp-2 mb-3">{caseItem.description}</p>
                )}

                {/* 操作按钮 */}
                <div className="flex items-center justify-between pt-3 border-t border-gray-100">
                  <div className="flex items-center gap-1">
                    <button
                      onClick={() => toggleActive(caseItem)}
                      className={`p-2 rounded-lg transition-colors ${
                        caseItem.is_active
                          ? 'text-green-600 hover:bg-green-50'
                          : 'text-gray-400 hover:bg-gray-50'
                      }`}
                      title={caseItem.is_active ? '点击隐藏' : '点击显示'}
                    >
                      {caseItem.is_active ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
                    </button>
                    <button
                      onClick={() => openEditModal(caseItem)}
                      className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                      title="编辑"
                    >
                      <Edit className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => handleDelete(caseItem.id)}
                      className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                      title="删除"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                  <span className="text-xs text-gray-400">排序: {caseItem.sort_order}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 编辑模态框 */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
          <div className="bg-white rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            {/* 头部 */}
            <div className="flex items-center justify-between p-5 border-b border-gray-100">
              <h2 className="text-lg font-semibold text-gray-900">
                {editingCase ? '编辑案例' : '新增案例'}
              </h2>
              <button onClick={closeModal} className="p-2 hover:bg-gray-100 rounded-lg">
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* 表单内容 */}
            <div className="p-5 space-y-5">
              {/* 标题 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1.5">
                  标题 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                  className="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入案例标题"
                />
              </div>

              {/* 描述 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1.5">描述</label>
                <textarea
                  value={formData.description}
                  onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                  className="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                  rows={3}
                  placeholder="请输入案例描述"
                />
              </div>

              {/* 分类和排序 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">分类</label>
                  <select
                    value={formData.category}
                    onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value }))}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">选择分类</option>
                    {categories.map(cat => (
                      <option key={cat} value={cat}>{cat}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">排序</label>
                  <input
                    type="number"
                    value={formData.sort_order}
                    onChange={(e) => setFormData(prev => ({ ...prev, sort_order: parseInt(e.target.value) || 0 }))}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {/* 图片上传 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1.5">
                  图片 <span className="text-red-500">*</span>
                  <span className="text-gray-400 font-normal ml-1">（至少一张）</span>
                </label>
                
                {/* 已上传的图片 */}
                {formData.images.length > 0 && (
                  <div className="grid grid-cols-4 gap-2 mb-3">
                    {formData.images.map((img, index) => (
                      <div key={index} className="relative aspect-video rounded-lg overflow-hidden bg-gray-100 group">
                        <img src={img} alt="" className="w-full h-full object-cover" />
                        <button
                          type="button"
                          onClick={() => handleRemoveImage(index)}
                          className="absolute top-1 right-1 p-1 bg-red-500 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      </div>
                    ))}
                  </div>
                )}

                {/* 上传方式 */}
                <div className="space-y-3">
                  {/* 本地上传 */}
                  <div className="flex items-center gap-3">
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept="image/*"
                      onChange={handleImageUpload}
                      className="hidden"
                    />
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      disabled={uploading}
                      className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors text-sm disabled:opacity-50"
                    >
                      {uploading ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Upload className="w-4 h-4" />
                      )}
                      本地上传
                    </button>
                  </div>

                  {/* URL添加 */}
                  <div className="flex items-center gap-2">
                    <input
                      type="text"
                      value={imageUrl}
                      onChange={(e) => setImageUrl(e.target.value)}
                      className="flex-1 px-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                      placeholder="输入图片URL"
                    />
                    <button
                      type="button"
                      onClick={handleAddImageUrl}
                      className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm"
                    >
                      添加
                    </button>
                  </div>
                </div>
              </div>

              {/* 状态 */}
              <div className="flex items-center gap-3">
                <input
                  type="checkbox"
                  id="is_active"
                  checked={formData.is_active}
                  onChange={(e) => setFormData(prev => ({ ...prev, is_active: e.target.checked }))}
                  className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <label htmlFor="is_active" className="text-sm text-gray-700">显示在前台页面</label>
              </div>
            </div>

            {/* 底部按钮 */}
            <div className="flex items-center justify-end gap-3 p-5 border-t border-gray-100">
              <button
                onClick={closeModal}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors text-sm"
              >
                取消
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="inline-flex items-center gap-2 px-5 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium disabled:opacity-50"
              >
                {saving ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Save className="w-4 h-4" />
                    保存
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
