'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Save, FileText, LayoutTemplate, Sparkles, ChevronDown, ChevronUp, Loader2 } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { toast } from '@/lib/toast';
import { useTranslation } from '@/hooks/useTranslation';
import { createFormDefinition, type CreateFormDefinitionDto } from '@/services/api/form-management';
import { getTopLevelOrganizations, type Department } from '@/services/api/organization';
import { ApiClientError } from '@/lib/api-client';

export default function NewFormDefinitionPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [topLevelDepts, setTopLevelDepts] = useState<Department[]>([]);
  const [loadingOrgs, setLoadingOrgs] = useState(true);
  const [formData, setFormData] = useState<CreateFormDefinitionDto>({
    key: '',
    name: '',
    description: '',
    category: 'OTHER',
    organizationId: undefined,
    requiresApproval: true,
  });
  
  // Store auto-generated key to avoid regenerating on every render
  const [autoGeneratedKey, setAutoGeneratedKey] = useState('');

  // Load organizations
  useEffect(() => {
    const loadOrganizations = async () => {
      try {
        setLoadingOrgs(true);
        const orgs = await getTopLevelOrganizations();
        setTopLevelDepts(orgs);
      } catch (error) {
        console.error('Failed to load organizations:', error);
        toast.error(t.forms.messages.loadFailed);
      } finally {
        setLoadingOrgs(false);
      }
    };
    loadOrganizations();
  }, [t]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validate required fields
    if (!formData.name) {
      toast.error(t.forms.messages.fillRequired);
      return;
    }

    // Auto-generate key if not provided (or if user provided one, validate it)
    let key = formData.key.trim();
    if (!key) {
      // Use the stored auto-generated key, or generate a new one
      key = autoGeneratedKey || generateKeyFromName(formData.name);
    } else {
      // User provided a custom key - validate format
      if (!/^[a-z][a-z0-9_]*$/.test(key)) {
        toast.error(t.forms.create.keyFormatError);
        setShowAdvanced(true);
        return;
      }
    }

    try {
      setLoading(true);
      const result = await createFormDefinition({ ...formData, key });
      toast.success(t.forms.messages.formCreated);
      // Navigate to designer
      router.push(`/forms/definitions/${result.id}/design`);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.submitFailed}: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  // Generate a unique key: prefix (from name if possible) + timestamp + random
  const generateKeyFromName = (name: string) => {
    // Try to extract English letters from name
    const prefix = name
      .toLowerCase()
      .replace(/\s+/g, '_')
      .replace(/[^a-z0-9_]/g, '')
      .replace(/^[0-9_]+/, '')
      .slice(0, 20); // Limit prefix length
    
    // Generate unique suffix: timestamp (base36) + random
    const timestamp = Date.now().toString(36).slice(-4);
    const random = Math.random().toString(36).slice(2, 6);
    
    // If we have a prefix from English name, use it; otherwise use "form"
    const basePrefix = prefix || 'form';
    return `${basePrefix}_${timestamp}${random}`;
  };

  return (
    <div className="h-full flex flex-col" style={{ backgroundColor: '#f7f8fa' }}>
      {/* 标题栏 - 飞书风格，固定 h-12 */}
      <div className="bg-white border-b" style={{ borderColor: '#e5e6eb' }}>
        <div className="px-6 h-12">
          <div className="flex items-center justify-between h-full">
            {/* 左侧：返回按钮 + 标题 */}
            <div className="flex items-center gap-3">
              <button
                type="button"
                onClick={() => router.back()}
                className="p-1.5 rounded transition-colors"
                style={{ backgroundColor: '#ffffff' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.backgroundColor = '#f7f8fa';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = '#ffffff';
                }}
              >
                <ArrowLeft className="w-4 h-4" style={{ color: '#646a73' }} />
              </button>
              
              <h1 className="text-base font-semibold flex items-center" style={{ color: '#1f2329' }}>
                <FileText className="w-5 h-5 mr-2 text-blue-600" />
                {t.forms.create.title}
              </h1>
            </div>
            
            {/* 右侧：操作按钮 */}
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => router.back()}
                disabled={loading}
                className="px-4 py-1.5 rounded-lg text-sm font-medium transition-all"
                style={{ 
                  backgroundColor: '#f7f8fa',
                  color: '#1f2329',
                  border: 'none',
                  cursor: loading ? 'not-allowed' : 'pointer',
                  opacity: loading ? 0.5 : 1
                }}
                onMouseEnter={(e) => {
                  if (!loading) {
                    e.currentTarget.style.backgroundColor = '#eff0f2';
                  }
                }}
                onMouseLeave={(e) => {
                  if (!loading) {
                    e.currentTarget.style.backgroundColor = '#f7f8fa';
                  }
                }}
              >
                {t.forms.common.cancel}
              </button>
              
              <button
                type="submit"
                form="create-form"
                disabled={loading}
                className="px-4 py-1.5 rounded-lg text-sm font-medium transition-all flex items-center gap-2"
                style={{ 
                  backgroundColor: loading ? '#c9cdd4' : '#3370ff',
                  color: '#ffffff',
                  border: 'none',
                  cursor: loading ? 'not-allowed' : 'pointer'
                }}
                onMouseEnter={(e) => {
                  if (!loading) {
                    e.currentTarget.style.backgroundColor = '#1e5eff';
                  }
                }}
                onMouseLeave={(e) => {
                  if (!loading) {
                    e.currentTarget.style.backgroundColor = '#3370ff';
                  }
                }}
              >
                {loading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    {t.forms.create.creating}
                  </>
                ) : (
                  <>
                    <Save className="w-4 h-4" />
                    {t.forms.create.createAndDesign}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 内容区域 - flex-1 自动占满剩余空间 */}
      <div className="flex-1 overflow-auto">
        <div className="max-w-4xl mx-auto p-6">
          <form id="create-form" onSubmit={handleSubmit} className="space-y-6">
            {/* 快速创建选项 */}
            <div className="grid grid-cols-2 gap-4">
              <button
                type="button"
                className="p-4 bg-white rounded-lg text-left transition-all"
                style={{ border: '2px solid #3370ff' }}
                onClick={() => {}}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(51, 112, 255, 0.15)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                }}
              >
                <div className="flex items-center gap-3 mb-2">
                  <Sparkles className="w-5 h-5 text-blue-600" />
                  <span className="font-medium" style={{ color: '#1f2329' }}>
                    {t.forms.create.blankCreate}
                  </span>
                </div>
                <p className="text-sm" style={{ color: '#8f959e' }}>
                  {t.forms.create.blankCreateDesc}
                </p>
              </button>
              
              <button
                type="button"
                className="p-4 bg-white rounded-lg text-left transition-all"
                style={{ border: '1px solid #e5e6eb' }}
                onClick={() => router.push('/forms/templates')}
                onMouseEnter={(e) => {
                  e.currentTarget.style.borderColor = '#c9cdd4';
                  e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.04)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.borderColor = '#e5e6eb';
                  e.currentTarget.style.boxShadow = 'none';
                }}
              >
                <div className="flex items-center gap-3 mb-2">
                  <LayoutTemplate className="w-5 h-5" style={{ color: '#646a73' }} />
                  <span className="font-medium" style={{ color: '#1f2329' }}>
                    {t.forms.create.useTemplate}
                  </span>
                </div>
                <p className="text-sm" style={{ color: '#8f959e' }}>
                  {t.forms.create.useTemplateDesc}
                </p>
              </button>
            </div>

            {/* 基本信息 */}
            <div className="bg-white rounded-lg shadow-sm p-6 space-y-5" style={{ border: '1px solid #e5e6eb' }}>
              <h2 className="text-base font-semibold flex items-center gap-2" style={{ color: '#1f2329' }}>
                <div className="w-1 h-5 bg-blue-600 rounded-full"></div>
                {t.forms.create.basicInfo}
              </h2>

              <div className="space-y-4">
                {/* 表单名称 */}
                <div className="space-y-2">
                  <Label htmlFor="name">
                    {t.forms.create.formName} <span className="text-red-500">*</span>
                  </Label>
                  <input
                    id="name"
                    type="text"
                    value={formData.name}
                    onChange={(e) => {
                      const name = e.target.value;
                      setFormData({ ...formData, name });
                      // Generate a new auto key when name changes and no custom key is set
                      if (!formData.key) {
                        setAutoGeneratedKey(generateKeyFromName(name));
                      }
                    }}
                    placeholder={t.forms.create.formNamePlaceholder}
                    required
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all"
                    style={{ 
                      backgroundColor: '#ffffff',
                      border: '1px solid #e5e6eb',
                      color: '#1f2329'
                    }}
                    onFocus={(e) => {
                      e.currentTarget.style.borderColor = '#3370ff';
                      e.currentTarget.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.currentTarget.style.borderColor = '#e5e6eb';
                      e.currentTarget.style.boxShadow = 'none';
                    }}
                  />
                  {formData.name && !showAdvanced && (
                    <p className="text-xs" style={{ color: '#8f959e' }}>
                      {t.forms.create.keyAutoGenerated}
                    </p>
                  )}
                </div>

                {/* 表单描述 */}
                <div className="space-y-2">
                  <Label htmlFor="description">{t.forms.create.formDescription}</Label>
                  <textarea
                    id="description"
                    value={formData.description || ''}
                    onChange={(e) =>
                      setFormData({ ...formData, description: e.target.value })
                    }
                    placeholder={t.forms.create.formDescriptionPlaceholder}
                    rows={3}
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all resize-none"
                    style={{ 
                      backgroundColor: '#ffffff',
                      border: '1px solid #e5e6eb',
                      color: '#1f2329'
                    }}
                    onFocus={(e) => {
                      e.currentTarget.style.borderColor = '#3370ff';
                      e.currentTarget.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.currentTarget.style.borderColor = '#e5e6eb';
                      e.currentTarget.style.boxShadow = 'none';
                    }}
                  />
                </div>

                {/* 分类 */}
                <div className="space-y-2">
                  <Label htmlFor="category">{t.forms.definition.category}</Label>
                  <select
                    id="category"
                    value={formData.category}
                    onChange={(e) =>
                      setFormData({ ...formData, category: e.target.value })
                    }
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all cursor-pointer"
                    style={{ 
                      backgroundColor: '#ffffff',
                      border: '1px solid #e5e6eb',
                      color: '#1f2329'
                    }}
                    onFocus={(e) => {
                      e.currentTarget.style.borderColor = '#3370ff';
                    }}
                    onBlur={(e) => {
                      e.currentTarget.style.borderColor = '#e5e6eb';
                    }}
                  >
                    <option value="HR">{t.forms.definition.categories.HR}</option>
                    <option value="FINANCE">{t.forms.definition.categories.FINANCE}</option>
                    <option value="IT">{t.forms.definition.categories.IT}</option>
                    <option value="ADMIN">{t.forms.definition.categories.ADMIN}</option>
                    <option value="OTHER">{t.forms.definition.categories.OTHER}</option>
                  </select>
                </div>

                {/* 组织归属 */}
                <div className="space-y-2">
                  <Label htmlFor="organizationId">
                    {t.forms.create.belongOrganization}
                    <span className="ml-2 text-xs font-normal" style={{ color: '#8f959e' }}>
                      ({t.forms.common.optional})
                    </span>
                  </Label>
                  <select
                    id="organizationId"
                    value={formData.organizationId || ''}
                    onChange={(e) => {
                      const value = e.target.value;
                      setFormData({ ...formData, organizationId: value ? value : undefined });
                    }}
                    disabled={loadingOrgs}
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all cursor-pointer"
                    style={{ 
                      backgroundColor: '#ffffff',
                      border: '1px solid #e5e6eb',
                      color: '#1f2329',
                      opacity: loadingOrgs ? 0.6 : 1
                    }}
                    onFocus={(e) => {
                      e.currentTarget.style.borderColor = '#3370ff';
                    }}
                    onBlur={(e) => {
                      e.currentTarget.style.borderColor = '#e5e6eb';
                    }}
                  >
                    <option value="">{t.forms.create.platformLevelForm}</option>
                    {topLevelDepts.map((dept) => (
                      <option key={dept.id} value={dept.organizationId}>
                        {dept.name} ({dept.code})
                      </option>
                    ))}
                  </select>
                  <p className="text-xs" style={{ color: '#8f959e' }}>
                    {t.forms.create.organizationHint}
                  </p>
                </div>

                {/* 高级选项切换 */}
                <button
                  type="button"
                  onClick={() => setShowAdvanced(!showAdvanced)}
                  className="flex items-center gap-1 text-sm transition-colors"
                  style={{ color: '#646a73' }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.color = '#1f2329';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.color = '#646a73';
                  }}
                >
                  {showAdvanced ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                  {t.forms.create.advancedOptions}
                </button>

                {/* 高级选项：自定义表单 Key */}
                {showAdvanced && (
                  <div className="space-y-2 pl-4" style={{ borderLeft: '2px solid #e5e6eb' }}>
                    <Label htmlFor="key">
                      {t.forms.create.formKey}
                      <span className="ml-2 text-xs font-normal" style={{ color: '#8f959e' }}>
                        ({t.forms.common.optional})
                      </span>
                    </Label>
                    <input
                      id="key"
                      type="text"
                      value={formData.key}
                      onChange={(e) =>
                        setFormData({ ...formData, key: e.target.value.toLowerCase() })
                      }
                      placeholder={autoGeneratedKey || 'form_xxxx'}
                      className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all font-mono"
                      style={{ 
                        backgroundColor: '#ffffff',
                        border: '1px solid #e5e6eb',
                        color: '#1f2329'
                      }}
                      onFocus={(e) => {
                        e.currentTarget.style.borderColor = '#3370ff';
                        e.currentTarget.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                      }}
                      onBlur={(e) => {
                        e.currentTarget.style.borderColor = '#e5e6eb';
                        e.currentTarget.style.boxShadow = 'none';
                      }}
                    />
                    <p className="text-xs" style={{ color: '#8f959e' }}>
                      {t.forms.create.keyCustomHint}
                    </p>
                  </div>
                )}
              </div>
            </div>

            {/* 审批配置 */}
            <div className="bg-white rounded-lg shadow-sm p-6 space-y-5" style={{ border: '1px solid #e5e6eb' }}>
              <h2 className="text-base font-semibold flex items-center gap-2" style={{ color: '#1f2329' }}>
                <div className="w-1 h-5 bg-purple-600 rounded-full"></div>
                {t.forms.create.approvalConfig}
              </h2>

              <div className="flex items-center justify-between py-2">
                <div>
                  <label htmlFor="requiresApproval" className="text-base font-medium cursor-pointer" style={{ color: '#1f2329' }}>
                    {t.forms.create.requiresApproval}
                  </label>
                  <p className="text-sm mt-1" style={{ color: '#8f959e' }}>
                    {t.forms.create.requiresApprovalHint}
                  </p>
                </div>
                
                {/* Switch */}
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    id="requiresApproval"
                    type="checkbox"
                    className="sr-only peer"
                    checked={formData.requiresApproval}
                    onChange={(e) =>
                      setFormData({ ...formData, requiresApproval: e.target.checked })
                    }
                  />
                  <div className="w-11 h-6 rounded-full peer transition-all"
                    style={{ 
                      backgroundColor: formData.requiresApproval ? '#3370ff' : '#e5e6eb'
                    }}>
                    <div 
                      className="absolute top-0.5 left-0.5 bg-white w-5 h-5 rounded-full transition-transform"
                      style={{
                        transform: formData.requiresApproval ? 'translateX(20px)' : 'translateX(0)'
                      }}
                    />
                  </div>
                </label>
              </div>

              {formData.requiresApproval && (
                <div className="p-4 rounded-lg" style={{ backgroundColor: 'rgba(51, 112, 255, 0.06)', border: '1px solid rgba(51, 112, 255, 0.2)' }}>
                  <p className="text-sm" style={{ color: '#3370ff' }}>
                    💡 {t.forms.create.approvalTip}
                  </p>
                </div>
              )}
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
