'use client';

import { useState } from 'react';
import { Bug, Lightbulb, TrendingUp, HelpCircle, Loader2, CheckCircle } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';
import { toast } from '@/lib/toast';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  createFeedback,
  FeedbackType,
  CreateFeedbackDto,
  ApiClientError,
} from '@/services/api/feedback';

interface FeedbackModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess?: () => void;
}

// 反馈类型配置
const FEEDBACK_TYPES = [
  { type: FeedbackType.BUG, icon: Bug, color: 'text-red-500', bgColor: 'bg-red-50', borderColor: 'border-red-200' },
  { type: FeedbackType.FEATURE, icon: Lightbulb, color: 'text-purple-500', bgColor: 'bg-purple-50', borderColor: 'border-purple-200' },
  { type: FeedbackType.IMPROVEMENT, icon: TrendingUp, color: 'text-blue-500', bgColor: 'bg-blue-50', borderColor: 'border-blue-200' },
  { type: FeedbackType.OTHER, icon: HelpCircle, color: 'text-gray-500', bgColor: 'bg-gray-50', borderColor: 'border-gray-200' },
];

export function FeedbackModal({ open, onOpenChange, onSuccess }: FeedbackModalProps) {
  const { t } = useTranslation();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  
  // 表单状态
  const [selectedType, setSelectedType] = useState<FeedbackType | null>(null);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [attachments, setAttachments] = useState<string[]>([]);
  const [attachmentInput, setAttachmentInput] = useState('');

  // 表单验证错误
  const [errors, setErrors] = useState<{
    type?: string;
    title?: string;
    content?: string;
    attachments?: string;
  }>({});

  // 获取类型标签
  const getTypeLabel = (type: FeedbackType) => {
    const labels = {
      [FeedbackType.BUG]: t.feedback?.typeBug,
      [FeedbackType.FEATURE]: t.feedback?.typeFeature,
      [FeedbackType.IMPROVEMENT]: t.feedback?.typeImprovement,
      [FeedbackType.OTHER]: t.feedback?.typeOther,
    };
    return labels[type] || type;
  };

  // 验证表单
  const validateForm = (): boolean => {
    const newErrors: typeof errors = {};

    if (!selectedType) {
      newErrors.type = t.feedback?.error?.typeRequired || 'Please select a feedback type';
    }

    if (!title.trim()) {
      newErrors.title = t.feedback?.error?.titleRequired || 'Please enter a title';
    } else if (title.length > 200) {
      newErrors.title = t.feedback?.error?.titleTooLong || 'Title cannot exceed 200 characters';
    }

    if (!content.trim()) {
      newErrors.content = t.feedback?.error?.contentRequired || 'Please enter a description';
    } else if (content.length > 5000) {
      newErrors.content = t.feedback?.error?.contentTooLong || 'Content cannot exceed 5000 characters';
    }

    if (attachments.length > 5) {
      newErrors.attachments =
        t.feedback?.error?.attachmentsExceedLimit || 'Maximum 5 images allowed';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const isValidAttachmentUrl = (value: string) => {
    try {
      const url = new URL(value);
      return url.protocol === 'http:' || url.protocol === 'https:';
    } catch {
      return false;
    }
  };

  const handleAddAttachment = () => {
    const trimmed = attachmentInput.trim();
    if (!trimmed) return;

    if (!isValidAttachmentUrl(trimmed)) {
      setErrors((prev) => ({
        ...prev,
        attachments: t.feedback?.error?.attachmentUrlInvalid || 'Invalid URL format',
      }));
      return;
    }

    if (attachments.length >= 5) {
      setErrors((prev) => ({
        ...prev,
        attachments: t.feedback?.error?.attachmentsExceedLimit || 'Maximum 5 images allowed',
      }));
      return;
    }

    setAttachments((prev) => [...prev, trimmed]);
    setAttachmentInput('');
    setErrors((prev) => ({ ...prev, attachments: undefined }));
  };

  const handleRemoveAttachment = (index: number) => {
    setAttachments((prev) => prev.filter((_, i) => i !== index));
    setErrors((prev) => ({ ...prev, attachments: undefined }));
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!validateForm()) return;

    setIsSubmitting(true);
    try {
      const data: CreateFeedbackDto = {
        type: selectedType!,
        title: title.trim(),
        content: content.trim(),
        attachments,
      };

      await createFeedback(data);
      
      // 显示成功状态
      setIsSuccess(true);
      toast.success(
        t.feedback?.form?.success || 'Feedback Submitted',
        {
          description:
            t.feedback?.form?.successDesc ||
            'Thank you for your feedback! We will process it as soon as possible.',
        },
      );

      // 延迟关闭弹窗
      setTimeout(() => {
        resetForm();
        onOpenChange(false);
        setIsSuccess(false);
        onSuccess?.();
      }, 1500);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(error.message);
        
        // 处理字段级错误
        if (error.isValidationError() && error.errors) {
          const fieldErrors: typeof errors = {};
          error.errors.forEach((e) => {
            if (e.field === 'title') fieldErrors.title = e.message;
            if (e.field === 'content') fieldErrors.content = e.message;
            if (e.field === 'type') fieldErrors.type = e.message;
          });
          setErrors(fieldErrors);
        }
      } else {
        toast.error(t.feedback?.error?.submitFailed || 'Failed to submit feedback');
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  // 重置表单
  const resetForm = () => {
    setSelectedType(null);
    setTitle('');
    setContent('');
    setAttachments([]);
    setAttachmentInput('');
    setErrors({});
  };

  // 关闭弹窗时重置
  const handleOpenChange = (open: boolean) => {
    if (!open) {
      resetForm();
      setIsSuccess(false);
    }
    onOpenChange(open);
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent
        className="sm:max-w-[520px] max-h-[90vh] overflow-y-auto"
        data-testid="feedback-modal"
      >
        <DialogHeader>
          <DialogTitle className="text-lg font-semibold">
            {t.feedback?.form?.title || 'Submit Feedback'}
          </DialogTitle>
          <DialogDescription className="text-sm text-gray-500">
            {t.feedback?.subtitle || 'Submit feedback and suggestions'}
          </DialogDescription>
        </DialogHeader>

        {isSuccess ? (
          // 成功状态
          <div className="py-12 text-center">
            <CheckCircle className="w-16 h-16 mx-auto text-green-500 mb-4" />
            <h3 className="text-lg font-medium text-gray-900">
              {t.feedback?.form?.success || 'Feedback Submitted'}
            </h3>
            <p className="mt-2 text-sm text-gray-500">
              {t.feedback?.form?.successDesc ||
                'Thank you for your feedback! We will process it as soon as possible.'}
            </p>
          </div>
        ) : (
          // 表单内容
          <div className="space-y-5 py-2">
            {/* 反馈类型选择 */}
            <div className="space-y-2" data-field="type">
              <Label className="text-sm font-medium">
                {t.feedback?.form?.type || 'Feedback Type'} <span className="text-red-500">*</span>
              </Label>
              <div className="grid grid-cols-2 gap-3">
                {FEEDBACK_TYPES.map(({ type, icon: Icon, color, bgColor, borderColor }) => (
                  <button
                    key={type}
                    type="button"
                    onClick={() => {
                      setSelectedType(type);
                      setErrors((prev) => ({ ...prev, type: undefined }));
                    }}
                    className={`flex items-center gap-3 p-3 rounded-lg border-2 transition-all ${
                      selectedType === type
                        ? `${bgColor} ${borderColor} ${color}`
                        : 'border-gray-200 hover:border-gray-300 bg-white'
                    }`}
                  >
                    <Icon className={`w-5 h-5 ${selectedType === type ? color : 'text-gray-400'}`} />
                    <span className={`text-sm font-medium ${selectedType === type ? color : 'text-gray-700'}`}>
                      {getTypeLabel(type)}
                    </span>
                  </button>
                ))}
              </div>
              {errors.type && (
                <p className="text-sm text-red-500">{errors.type}</p>
              )}
            </div>

            {/* 标题 */}
            <div className="space-y-2">
              <Label htmlFor="feedback-title" className="text-sm font-medium">
                {t.feedback?.form?.feedbackTitle || 'Title'} <span className="text-red-500">*</span>
              </Label>
              <Input
                id="feedback-title"
                name="title"
                value={title}
                onChange={(e) => {
                  setTitle(e.target.value);
                  setErrors((prev) => ({ ...prev, title: undefined }));
                }}
                placeholder={t.feedback?.form?.feedbackTitlePlaceholder || 'Briefly describe your feedback'}
                maxLength={200}
                className={errors.title ? 'border-red-500' : ''}
              />
              <div className="flex justify-between text-xs text-gray-400">
                {errors.title ? (
                  <span className="text-red-500">{errors.title}</span>
                ) : (
                  <span></span>
                )}
                <span>{title.length}/200</span>
              </div>
            </div>

            {/* 详细描述 */}
            <div className="space-y-2">
              <Label htmlFor="feedback-content" className="text-sm font-medium">
                {t.feedback?.form?.content || 'Description'} <span className="text-red-500">*</span>
              </Label>
              <Textarea
                id="feedback-content"
                name="content"
                value={content}
                onChange={(e) => {
                  setContent(e.target.value);
                  setErrors((prev) => ({ ...prev, content: undefined }));
                }}
                placeholder={t.feedback?.form?.contentPlaceholder || 'Please describe your issue or suggestion in detail...'}
                rows={5}
                maxLength={5000}
                className={`resize-none ${errors.content ? 'border-red-500' : ''}`}
              />
              <div className="flex justify-between text-xs text-gray-400">
                {errors.content ? (
                  <span className="text-red-500">{errors.content}</span>
                ) : (
                  <span></span>
                )}
                <span>{content.length}/5000</span>
              </div>
            </div>

            {/* 附件链接 */}
            <div className="space-y-2" data-field="attachments">
              <Label htmlFor="feedback-attachments" className="text-sm font-medium">
                {t.feedback?.form?.attachments || 'Attachment URLs'}
              </Label>
              <div className="flex gap-2">
                <Input
                  id="feedback-attachments"
                  value={attachmentInput}
                  onChange={(e) => {
                    setAttachmentInput(e.target.value);
                    setErrors((prev) => ({ ...prev, attachments: undefined }));
                  }}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      handleAddAttachment();
                    }
                  }}
                  placeholder={
                    t.feedback?.form?.attachmentsPlaceholder || 'https://example.com/screenshot.png'
                  }
                />
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleAddAttachment}
                  disabled={isSubmitting}
                >
                  {t.common?.add || 'Add'}
                </Button>
              </div>
              <div className="text-xs text-gray-400">
                {t.feedback?.form?.attachmentsHint || 'Up to 5 URLs'}
              </div>
              {errors.attachments && (
                <p className="text-sm text-red-500">{errors.attachments}</p>
              )}
              {attachments.length > 0 && (
                <div className="space-y-2">
                  {attachments.map((url, index) => (
                    <div
                      key={`${url}-${index}`}
                      className="flex items-center justify-between gap-2 rounded-md border border-gray-200 px-3 py-2 text-sm text-gray-700"
                    >
                      <span className="truncate">{url}</span>
                      <button
                        type="button"
                        onClick={() => handleRemoveAttachment(index)}
                        className="text-xs text-gray-500 hover:text-gray-700"
                      >
                        {t.common?.remove || 'Remove'}
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* 按钮区域 */}
            <div className="flex justify-end gap-3 pt-4 border-t">
              <Button
                type="button"
                variant="outline"
                data-action="cancel"
                onClick={() => handleOpenChange(false)}
                disabled={isSubmitting}
              >
                {t.feedback?.form?.cancel || 'Cancel'}
              </Button>
              <Button
                type="button"
                data-action="submit"
                onClick={handleSubmit}
                disabled={isSubmitting}
                className="bg-blue-600 hover:bg-blue-700"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    {t.feedback?.form?.submitting || 'Submitting...'}
                  </>
                ) : (
                  t.feedback?.form?.submit || 'Submit Feedback'
                )}
              </Button>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}

export default FeedbackModal;
