'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  Languages,
  Plus,
  Edit,
  Trash2,
  CheckCircle2,
  AlertCircle,
  Globe,
  FileText,
  ChevronRight,
  Upload,
  Download,
  RefreshCw,
  Check,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { toast } from '@/lib/toast';
import { useConfirm } from '@/components/common/feedback/ConfirmProvider';
import { PageState } from '@/components/common/feedback/PageState';
import { useTranslation } from '@/hooks/useTranslation';
import {
  getForms,
  getFormVersions,
  getFormTranslations,
  upsertFormTranslation,
  deleteFormTranslation,
  checkTranslationCompleteness,
  batchImportTranslations,
  type FormDefinition,
  type FormVersion,
  type FormTranslation,
} from '@/services/api/forms';
import { ApiClientError } from '@/lib/api-client';

// 支持的语言列表
const SUPPORTED_LOCALES = [
  { code: 'zh-CN', label: '简体中文' },
  { code: 'zh-TW', label: '繁体中文' },
  { code: 'en-US', label: 'English' },
  { code: 'ja-JP', label: '日本語' },
  { code: 'ko-KR', label: '한국어' },
];

interface TranslationWithCheck extends FormTranslation {
  completeness?: {
    isComplete: boolean;
    coverage: number;
    totalRequired: number;
    translated: number;
    missingKeys: string[];
  };
}

export default function FormTranslationsPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const [forms, setForms] = useState<FormDefinition[]>([]);
  const [versions, setVersions] = useState<FormVersion[]>([]);
  const [selectedForm, setSelectedForm] = useState<string>('');
  const [selectedVersion, setSelectedVersion] = useState<number>(0);
  const [translations, setTranslations] = useState<TranslationWithCheck[]>([]);
  const [loading, setLoading] = useState(false);
  const confirm = useConfirm();
  
  // 对话框状态
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingLocale, setEditingLocale] = useState<string | null>(null);
  const [dialogData, setDialogData] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);

  // 导入对话框
  const [importDialogOpen, setImportDialogOpen] = useState(false);
  const [importData, setImportData] = useState('');
  const [importing, setImporting] = useState(false);

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

  useEffect(() => {
    if (selectedForm) {
      loadVersions(selectedForm);
    }
  }, [selectedForm]);

  useEffect(() => {
    if (selectedForm && selectedVersion > 0) {
      loadTranslations();
    }
  }, [selectedForm, selectedVersion]);

  const loadForms = async () => {
    try {
      const response = await getForms({ limit: 100 });
      setForms(response.items);
      if (response.items.length > 0) {
        setSelectedForm(response.items[0].key);
      }
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.common.loadFailed}: ${error.message}`);
      }
    }
  };

  const loadVersions = async (formKey: string) => {
    try {
      const data = await getFormVersions(formKey);
      setVersions(data);
      const publishedVersions = data.filter(v => v.status === 'PUBLISHED');
      const defaultVersion = data.find(v => v.isDefault) || publishedVersions[0] || data[0];
      if (defaultVersion) {
        setSelectedVersion(defaultVersion.version);
      }
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.common.loadFailed}: ${error.message}`);
      }
    }
  };

  const loadTranslations = async () => {
    try {
      setLoading(true);
      const response = await getFormTranslations(selectedForm, selectedVersion);
      const items = response.items || [];
      
      // 为每个翻译检查完整性
      const translationsWithCheck: TranslationWithCheck[] = await Promise.all(
        items.map(async (t) => {
          try {
            const completeness = await checkTranslationCompleteness(selectedForm, selectedVersion, t.locale);
            return { ...t, completeness };
          } catch {
            return t;
          }
        })
      );
      
      setTranslations(translationsWithCheck);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`加载翻译失败: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleOpenDialog = (locale: string | null = null, existingData?: Record<string, string>) => {
    setEditingLocale(locale);
    setDialogData(existingData || {});
    setDialogOpen(true);
  };

  const handleSaveTranslation = async () => {
    if (!selectedForm || !selectedVersion || !editingLocale) return;

    try {
      setSaving(true);
      await upsertFormTranslation(selectedForm, selectedVersion, editingLocale, {
        translations: dialogData,
      });
      toast.success('翻译保存成功');
      setDialogOpen(false);
      loadTranslations();
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`保存失败: ${error.message}`);
      }
    } finally {
      setSaving(false);
    }
  };

  const handleDeleteTranslation = async (locale: string) => {
    if (!selectedForm || !selectedVersion) return;
    const confirmed = await confirm({
      title: `确定要删除 ${getLocaleLabel(locale)} 翻译吗？`,
      variant: 'danger',
    });
    if (!confirmed) return;

    try {
      await deleteFormTranslation(selectedForm, selectedVersion, locale);
      toast.success('翻译已删除');
      loadTranslations();
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`删除失败: ${error.message}`);
      }
    }
  };

  const handleBatchImport = async () => {
    if (!selectedForm || !selectedVersion || !importData) return;

    try {
      setImporting(true);
      const parsed = JSON.parse(importData);
      const result = await batchImportTranslations(selectedForm, selectedVersion, {
        translations: parsed,
        overwrite: true,
      });
      toast.success(`导入成功: 创建 ${result.created} 个, 更新 ${result.updated} 个`);
      setImportDialogOpen(false);
      setImportData('');
      loadTranslations();
    } catch (error) {
      if (error instanceof SyntaxError) {
        toast.error('JSON 格式错误，请检查输入');
      } else if (error instanceof ApiClientError) {
        toast.error(`导入失败: ${error.message}`);
      }
    } finally {
      setImporting(false);
    }
  };

  const getLocaleLabel = (locale: string) => {
    return SUPPORTED_LOCALES.find(l => l.code === locale)?.label || locale;
  };

  const getAvailableLocales = () => {
    const existingLocales = translations.map(t => t.locale);
    return SUPPORTED_LOCALES.filter(l => !existingLocales.includes(l.code));
  };

  const selectedFormData = forms.find(f => f.key === selectedForm);
  const selectedVersionData = versions.find(v => v.version === selectedVersion);

  return (
    <div className="p-8 space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <Languages className="w-6 h-6 text-blue-600" />
            翻译管理
          </h1>
          <p className="text-sm text-gray-600 mt-1">
            管理表单版本的多语言翻译
          </p>
        </div>
        {selectedForm && selectedVersion > 0 && (
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={() => setImportDialogOpen(true)}>
              <Upload className="w-4 h-4 mr-2" />
              批量导入
            </Button>
          </div>
        )}
      </div>

      {/* 表单和版本选择 */}
      <div className="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
        <div className="flex items-center gap-4">
          <div className="flex-1">
            <Label className="text-sm font-medium text-gray-600">选择表单</Label>
            <Select value={selectedForm} onValueChange={setSelectedForm}>
              <SelectTrigger className="mt-1">
                <SelectValue placeholder="请选择表单" />
              </SelectTrigger>
              <SelectContent>
                {forms.map((form) => (
                  <SelectItem key={form.key} value={form.key}>
                    <div className="flex items-center gap-2">
                      <FileText className="w-4 h-4" />
                      <span>{form.name}</span>
                      <span className="text-gray-500 font-mono text-xs">({form.key})</span>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="w-48">
            <Label className="text-sm font-medium text-gray-600">选择版本</Label>
            <Select
              value={selectedVersion.toString()}
              onValueChange={(val) => setSelectedVersion(parseInt(val))}
              disabled={versions.length === 0}
            >
              <SelectTrigger className="mt-1">
                <SelectValue placeholder="选择版本" />
              </SelectTrigger>
              <SelectContent>
                {versions.map((v) => (
                  <SelectItem key={v.version} value={v.version.toString()}>
                    v{v.version}
                    {v.isDefault && ' (默认)'}
                    {v.status === 'DRAFT' && ' - 草稿'}
                    {v.status === 'PUBLISHED' && ' - 已发布'}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {selectedFormData && (
          <div className="mt-4 pt-4 border-t border-gray-100 flex items-center gap-4 text-sm text-gray-600">
            <span>默认语言: {selectedFormData.defaultLocale}</span>
            <span>支持语言: {selectedFormData.supportedLocales.join(', ')}</span>
          </div>
        )}
      </div>

      {/* 翻译列表 */}
      {selectedForm && selectedVersion > 0 && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200">
          <div className="p-4 border-b border-gray-200 flex items-center justify-between">
            <h2 className="font-semibold text-gray-900">
              版本 v{selectedVersion} 的翻译
            </h2>
            {getAvailableLocales().length > 0 && (
              <Button
                size="sm"
                onClick={() => {
                  const availableLocale = getAvailableLocales()[0];
                  handleOpenDialog(availableLocale.code);
                }}
              >
                <Plus className="w-4 h-4 mr-1" />
                添加翻译
              </Button>
            )}
          </div>

          {loading ? (
            <div className="p-8 text-center text-gray-500">
              <RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2" />
              加载中...
            </div>
          ) : translations.length === 0 ? (
            <div className="p-12">
              <PageState
                variant="empty"
                title={t.forms.translationsPage.emptyTitle}
                description={t.forms.translationsPage.emptyDesc}
                actionLabel={t.forms.translationsPage.emptyAction}
                onAction={() => handleOpenDialog('en-US')}
                layout="center"
                className="border-0 bg-transparent"
              />
            </div>
          ) : (
            <div className="divide-y divide-gray-200">
              {translations.map((translation) => (
                <div
                  key={translation.id}
                  className="p-6 hover:bg-gray-50 transition-colors"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <Globe className="w-5 h-5 text-blue-600" />
                        <h3 className="text-lg font-semibold text-gray-900">
                          {getLocaleLabel(translation.locale)}
                        </h3>
                        <span className="text-sm text-gray-500 font-mono">
                          ({translation.locale})
                        </span>
                      </div>

                      {/* 翻译键值预览 */}
                      <div className="mt-3 space-y-1.5">
                        {Object.entries(translation.translations || {}).slice(0, 3).map(([key, value]) => (
                          <div key={key} className="text-sm flex gap-2">
                            <span className="text-gray-400 font-mono">{key}:</span>
                            <span className="text-gray-700 truncate max-w-md">{value as string}</span>
                          </div>
                        ))}
                        {Object.keys(translation.translations || {}).length > 3 && (
                          <div className="text-sm text-gray-400">
                            ... 还有 {Object.keys(translation.translations).length - 3} 个键
                          </div>
                        )}
                      </div>

                      {/* 完整性指示器 */}
                      {translation.completeness && (
                        <div className="mt-4 flex items-center gap-3">
                          {translation.completeness.isComplete ? (
                            <div className="flex items-center gap-1.5 text-green-600 text-sm">
                              <CheckCircle2 className="w-4 h-4" />
                              翻译完整
                            </div>
                          ) : (
                            <div className="flex items-center gap-1.5 text-yellow-600 text-sm">
                              <AlertCircle className="w-4 h-4" />
                              翻译不完整
                            </div>
                          )}
                          <div className="flex-1 max-w-xs">
                            <div className="flex items-center justify-between text-xs text-gray-600 mb-1">
                              <span>覆盖率</span>
                              <span>
                                {translation.completeness.translated}/{translation.completeness.totalRequired}
                                ({Math.round(translation.completeness.coverage * 100)}%)
                              </span>
                            </div>
                            <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                              <div
                                className={`h-full ${
                                  translation.completeness.isComplete ? 'bg-green-500' : 'bg-yellow-500'
                                }`}
                                style={{ width: `${translation.completeness.coverage * 100}%` }}
                              />
                            </div>
                          </div>
                          {translation.completeness.missingKeys.length > 0 && (
                            <span className="text-xs text-gray-500">
                              缺少: {translation.completeness.missingKeys.slice(0, 3).join(', ')}
                              {translation.completeness.missingKeys.length > 3 && '...'}
                            </span>
                          )}
                        </div>
                      )}
                    </div>

                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleOpenDialog(translation.locale, translation.translations)}
                      >
                        <Edit className="w-4 h-4 mr-1" />
                        编辑
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteTranslation(translation.locale)}
                        className="text-red-600 hover:text-red-700"
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* 编辑翻译对话框 */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingLocale && translations.find(t => t.locale === editingLocale)
                ? `编辑翻译 - ${getLocaleLabel(editingLocale)}`
                : `添加翻译 - ${editingLocale ? getLocaleLabel(editingLocale) : ''}`}
            </DialogTitle>
            <DialogDescription>
              编辑表单版本的翻译键值对
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            {/* 语言选择（仅新增时） */}
            {!translations.find(t => t.locale === editingLocale) && (
              <div className="space-y-2">
                <Label>语言</Label>
                <Select
                  value={editingLocale || ''}
                  onValueChange={setEditingLocale}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择语言" />
                  </SelectTrigger>
                  <SelectContent>
                    {getAvailableLocales().map(l => (
                      <SelectItem key={l.code} value={l.code}>
                        {l.label} ({l.code})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* 翻译键值编辑器 */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label>翻译内容</Label>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    const key = prompt('输入新的翻译键');
                    if (key) {
                      setDialogData(prev => ({ ...prev, [key]: '' }));
                    }
                  }}
                >
                  <Plus className="w-3 h-3 mr-1" />
                  添加键
                </Button>
              </div>
              
              {Object.keys(dialogData).length === 0 ? (
                <div className="py-8">
                  <PageState
                    variant="empty"
                    title={t.forms.translationsPage.emptyTitle}
                    description={t.forms.translationsPage.emptyKeysDesc}
                  />
                </div>
              ) : (
                <div className="space-y-3 max-h-60 overflow-y-auto">
                  {Object.entries(dialogData).map(([key, value]) => (
                    <div key={key} className="flex gap-2 items-start">
                      <div className="flex-1 space-y-1">
                        <Label className="text-xs font-mono text-gray-500">{key}</Label>
                        <Input
                          value={value as string}
                          onChange={(e) => setDialogData(prev => ({ ...prev, [key]: e.target.value }))}
                          placeholder={`${key} 的翻译...`}
                        />
                      </div>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="mt-6 text-red-500 hover:text-red-700"
                        onClick={() => {
                          const { [key]: _, ...rest } = dialogData;
                          setDialogData(rest);
                        }}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>
              取消
            </Button>
            <Button onClick={handleSaveTranslation} disabled={saving || !editingLocale}>
              {saving ? '保存中...' : '保存'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 批量导入对话框 */}
      <Dialog open={importDialogOpen} onOpenChange={setImportDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>批量导入翻译</DialogTitle>
            <DialogDescription>
              以 JSON 格式导入多语言翻译数据
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-700">
              <p className="font-medium mb-1">JSON 格式示例:</p>
              <pre className="bg-blue-100 p-2 rounded text-xs overflow-x-auto">
{`{
  "en-US": {
    "title": "Leave Application",
    "submit": "Submit"
  },
  "zh-TW": {
    "title": "請假申請",
    "submit": "提交"
  }
}`}
              </pre>
            </div>
            
            <Textarea
              value={importData}
              onChange={(e) => setImportData(e.target.value)}
              placeholder="粘贴 JSON 格式的翻译数据..."
              rows={10}
              className="font-mono text-sm"
            />
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setImportDialogOpen(false)}>
              取消
            </Button>
            <Button onClick={handleBatchImport} disabled={importing || !importData}>
              {importing ? '导入中...' : '导入'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
