'use client';

import { useState } from 'react';
import { X, Loader2, CheckCircle, AlertTriangle } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';
import { aiAssistantApi, type TicketCategory, type TicketPriority } from '@/lib/api/ai-assistant';

interface EscalateDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  conversationId: string | null;
}

const CATEGORIES: TicketCategory[] = ['IT', 'HR', 'ADMIN', 'FINANCE', 'OTHER'];
const PRIORITIES: TicketPriority[] = ['LOW', 'MEDIUM', 'HIGH', 'URGENT'];

/**
 * 升级工单对话框
 */
export function EscalateDialog({ open, onOpenChange, conversationId }: EscalateDialogProps) {
  const { t } = useTranslation();
  const [category, setCategory] = useState<TicketCategory>('IT');
  const [priority, setPriority] = useState<TicketPriority>('MEDIUM');
  const [description, setDescription] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [ticketId, setTicketId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async () => {
    if (!conversationId) {
      setError('No active conversation');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const response: any = await aiAssistantApi.escalate(conversationId, {
        category,
        priority,
        description: description.trim() || undefined,
      });

      setTicketId(response.data.id);
      setSuccess(true);
    } catch (err: any) {
      setError(err.response?.data?.error?.message || 'Failed to create ticket');
    } finally {
      setIsLoading(false);
    }
  };

  const handleClose = () => {
    setSuccess(false);
    setTicketId(null);
    setError(null);
    setCategory('IT');
    setPriority('MEDIUM');
    setDescription('');
    onOpenChange(false);
  };

  if (!open) return null;

  return (
    <>
      {/* 遮罩 */}
      <div 
        className="fixed inset-0 bg-black/50 z-[60]"
        onClick={handleClose}
      />

      {/* 对话框 */}
      <div 
        className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[60] w-full max-w-md bg-white rounded-xl shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h3 className="text-lg font-semibold text-gray-900">
            {'Request Human Assistance'}
          </h3>
          <button
            onClick={handleClose}
            className="p-1 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 内容 */}
        <div className="p-6">
          {success ? (
            <div className="text-center py-4">
              <CheckCircle className="w-16 h-16 text-green-500 mx-auto mb-4" />
              <p className="text-gray-900 font-medium mb-2">
                {'Ticket created successfully'}
              </p>
              {ticketId && (
                <p className="text-sm text-gray-500">
                  {'Ticket Number'}: {ticketId.slice(0, 8).toUpperCase()}
                </p>
              )}
              <button
                onClick={handleClose}
                className="mt-6 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                {'Close'}
              </button>
            </div>
          ) : (
            <>
              <p className="text-sm text-gray-500 mb-6">
                {'Your issue will be escalated to human support.'}
              </p>

              {/* 分类选择 */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {'Category'}
                </label>
                <div className="grid grid-cols-3 gap-2">
                  {CATEGORIES.map((cat) => (
                    <button
                      key={cat}
                      onClick={() => setCategory(cat)}
                      className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
                        category === cat
                          ? 'border-blue-500 bg-blue-50 text-blue-700'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      {t.aiAssistant?.escalate?.categories?.[cat] || cat}
                    </button>
                  ))}
                </div>
              </div>

              {/* 优先级选择 */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {'Priority'}
                </label>
                <div className="grid grid-cols-4 gap-2">
                  {PRIORITIES.map((pri) => (
                    <button
                      key={pri}
                      onClick={() => setPriority(pri)}
                      className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
                        priority === pri
                          ? 'border-blue-500 bg-blue-50 text-blue-700'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      {t.aiAssistant?.escalate?.priorities?.[pri] || pri}
                    </button>
                  ))}
                </div>
              </div>

              {/* 补充说明 */}
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {'Additional Information'}
                </label>
                <textarea
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  placeholder={'Please provide more details...'}
                  className="w-full h-24 px-3 py-2 border rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                />
              </div>

              {/* 错误提示 */}
              {error && (
                <div className="flex items-center gap-2 mb-4 px-3 py-2 bg-red-50 text-red-600 rounded-lg">
                  <AlertTriangle className="w-4 h-4" />
                  <span className="text-sm">{error}</span>
                </div>
              )}

              {/* 操作按钮 */}
              <div className="flex gap-3">
                <button
                  onClick={handleClose}
                  className="flex-1 px-4 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  {'Cancel'}
                </button>
                <button
                  onClick={handleSubmit}
                  disabled={isLoading}
                  className="flex-1 px-4 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
                >
                  {isLoading && <Loader2 className="w-4 h-4 animate-spin" />}
                  {'Confirm'}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
}

export default EscalateDialog;
