'use client';

import { useState, useEffect } from 'react';
import api from '@/lib/api';
import { Loader2, X, AlertTriangle } from 'lucide-react';
// 1. 引入 Hook
import { useLanguage } from '@/lib/i18n/LanguageContext';

interface TicketModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  defaultOrderId?: string;
}

export default function TicketModal({ isOpen, onClose, onSuccess, defaultOrderId = '' }: TicketModalProps) {
  // 2. 获取翻译函数
  const { t } = useLanguage();

  const [loading, setLoading] = useState<boolean>(false);
  const [errorMsg, setErrorMsg] = useState<string>('');
  
  const [form, setForm] = useState({
    order_id: '',
    type: 'refund',
    reason: ''
  });

  useEffect(() => {
    if (isOpen) {
      setForm({
        order_id: defaultOrderId || '',
        type: 'refund',
        reason: ''
      });
      setErrorMsg('');
    }
  }, [isOpen, defaultOrderId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setErrorMsg('');

    try {
      await api.post('/api/vas/ticket/create', form);
      
      if (onSuccess) onSuccess(); 
      onClose();
      
    } catch (error: any) {
      console.error(error);
      const msg = error.response?.data?.message || t('ticket.submit_error_default');
      setErrorMsg(msg);
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6">
      <div className="fixed inset-0 bg-black/40 backdrop-blur-sm transition-opacity" onClick={onClose} />

      <div className="relative w-full max-w-lg transform overflow-hidden rounded-xl bg-white text-left shadow-2xl transition-all animate-in zoom-in duration-200">
        
        {/* Header */}
        <div className="px-6 py-4 border-b flex justify-between items-center bg-gray-50">
          <h3 className="text-lg font-bold text-gray-900">{t('ticket.submit_modal_title')}</h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 transition">
            <X size={24} />
          </button>
        </div>
        
        <div className="p-6">
          {errorMsg && (
            <div className="mb-4 p-3 bg-red-50 text-red-700 text-sm rounded-lg flex items-center">
              <AlertTriangle size={16} className="mr-2 flex-shrink-0" />
              {errorMsg}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label className="block text-xs font-bold uppercase text-gray-500 mb-1">
                {t('ticket.order_id_label')} <span className="text-red-500">*</span>
              </label>
              <input
                type="text" required
                className="w-full rounded-lg border border-gray-300 py-2.5 px-3 text-gray-900 shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none text-sm bg-gray-50 focus:bg-white transition"
                value={form.order_id}
                onChange={e => setForm({ ...form, order_id: e.target.value })}
                placeholder={t('ticket.order_id_placeholder')}
              />
            </div>

            <div>
              <label className="block text-xs font-bold uppercase text-gray-500 mb-1">
                {t('ticket.type_label')} <span className="text-red-500">*</span>
              </label>
              <select
                className="w-full rounded-lg border border-gray-300 py-2.5 px-3 text-gray-900 shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none text-sm bg-white"
                value={form.type}
                onChange={e => setForm({ ...form, type: e.target.value })}
              >
                <option value="refund">{t('ticket.types.refund')}</option>
                <option value="dispute">{t('ticket.types.dispute')}</option>
                <option value="change_request">{t('ticket.types.change_request')}</option>
              </select>
            </div>

            <div>
              <label className="block text-xs font-bold uppercase text-gray-500 mb-1">
                {t('ticket.desc_label')} <span className="text-red-500">*</span>
              </label>
              <textarea
                required
                rows={4}
                className="w-full rounded-lg border border-gray-300 py-2.5 px-3 text-gray-900 shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none text-sm resize-none"
                placeholder={t('ticket.desc_placeholder')}
                value={form.reason}
                onChange={e => setForm({ ...form, reason: e.target.value })}
              />
            </div>

            <div className="pt-2 flex items-center justify-end gap-3 border-t mt-6">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-200 transition"
              >
                {t('common.cancel')}
              </button>
              <button
                type="submit"
                disabled={loading}
                className="inline-flex items-center justify-center px-6 py-2 text-sm font-bold text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed shadow-md transition"
              >
                {loading ? <Loader2 className="animate-spin w-4 h-4 mr-2" /> : null}
                {t('ticket.submit_btn')}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}