/**
 * filekorolheader: 新建企业弹窗组件 - 企业创建表单弹窗
 * 功能：企业信息表单、数据验证、API调用、状态管理
 * 路径：/central-config/tenant/enterprise-management/components/CreateEnterpriseDialog
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式，TypeScript类型安全
 */

'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Building2, Hash } from 'lucide-react';
import { toast } from 'sonner';
import { createEnterprise, CreateEnterpriseRequest } from './enterpriseApi';

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

export function CreateEnterpriseDialog({ open, onOpenChange, onSuccess }: CreateEnterpriseDialogProps) {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<CreateEnterpriseRequest>({
    company_name: '',
    tenant_code: '',
    company_type: '',
  });

  // 企业类型选项
  const companyTypes = [
    '个体工商户',
    '有限责任公司',
    '股份有限公司',
    '合伙企业',
    '其他',
  ];

  // 重置表单
  const resetForm = () => {
    setFormData({
      company_name: '',
      tenant_code: '',
      company_type: '',
    });
  };

  // 关闭弹窗
  const handleClose = () => {
    if (!loading) {
      onOpenChange(false);
      resetForm();
    }
  };

  // 处理输入变化
  const handleInputChange = (field: keyof CreateEnterpriseRequest, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 表单验证
  const validateForm = (): boolean => {
    if (!formData.company_name.trim()) {
      toast.error('请输入企业名称');
      return false;
    }
    if (!formData.tenant_code.trim()) {
      toast.error('请输入企业编码');
      return false;
    }
    if (!formData.company_type.trim()) {
      toast.error('请选择企业类型');
      return false;
    }
    return true;
  };

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

    try {
      setLoading(true);
      console.log('🏢 开始创建企业:', formData);

      // 调用API创建企业
      const result = await createEnterprise(formData);

      console.log('🏢 企业创建成功:', result);
      toast.success('企业创建成功！');

      // 关闭弹窗并重置表单
      handleClose();

      // 调用成功回调，刷新主页面数据
      onSuccess();

    } catch (error) {
      console.error('🏢 创建企业失败:', error);
      const errorMessage = error instanceof Error ? error.message : '创建企业失败，请稍后重试';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Building2 className="w-5 h-5 text-blue-600 dark:text-blue-400" />
            新建企业
          </DialogTitle>
          <DialogDescription>
            创建新企业账号，填写基本信息后系统将自动生成企业实例
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 企业名称 */}
          <div className="space-y-2">
            <Label htmlFor="company_name">企业名称 *</Label>
            <div className="relative">
              <Building2 className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                id="company_name"
                placeholder="请输入企业全称"
                value={formData.company_name}
                onChange={(e) => handleInputChange('company_name', e.target.value)}
                className="pl-10"
                disabled={loading}
              />
            </div>
          </div>

          {/* 企业编码 */}
          <div className="space-y-2">
            <Label htmlFor="tenant_code">企业编码 *</Label>
            <div className="relative">
              <Hash className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                id="tenant_code"
                placeholder="请输入企业唯一编码，如：SHNY001"
                value={formData.tenant_code}
                onChange={(e) => handleInputChange('tenant_code', e.target.value.toUpperCase())}
                className="pl-10"
                disabled={loading}
              />
            </div>
            <p className="text-xs text-muted-foreground">
              编码创建后不可修改，请谨慎填写
            </p>
          </div>

          {/* 企业类型 */}
          <div className="space-y-2">
            <Label htmlFor="company_type">企业类型 *</Label>
            <Select
              value={formData.company_type}
              onValueChange={(value) => handleInputChange('company_type', value)}
              disabled={loading}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择企业类型" />
              </SelectTrigger>
              <SelectContent>
                {companyTypes.map((type) => (
                  <SelectItem key={type} value={type}>
                    {type}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 温馨提示 */}
          <div className="p-4 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg">
            <p className="text-sm text-blue-800 dark:text-blue-200 font-medium mb-2">温馨提示：</p>
            <ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
              <li>• 企业创建后默认为待审核状态</li>
              <li>• 企业编码创建后不可修改，请确保准确无误</li>
              <li>• 创建成功后需要等待管理员审核</li>
            </ul>
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={loading}
            className="font-light"
          >
            取消
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={loading}
            className="font-light"
          >
            {loading ? '创建中...' : '创建企业'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}