'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { Card } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Building, FileText, CreditCard, User } from 'lucide-react';

import { EnterpriseInfoHeader } from './components/EnterpriseInfoHeader';
import { AuditStatusAlert } from './components/AuditStatusAlert';
import { BasicInfoForm } from './components/BasicInfoForm';
import { OtherInfoForm } from './components/OtherInfoForm';
import { BankInfoForm } from './components/BankInfoForm';
import { LegalInfoForm } from './components/LegalInfoForm';
import { SystemInfo } from './components/SystemInfo';
import { OperationTips } from './components/OperationTips';
import { Enterprise } from './types';
import { getAuthUser } from '@/stores/modules/auth';
import { fetchEnterpriseInfo, updateEnterpriseInfo, submitEnterpriseAudit, SubmitAuditRequest } from './components/enterpriseInfoApi';

export default function EnterpriseInfoPage() {
  const [enterprise, setEnterprise] = useState<Enterprise | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [formData, setFormData] = useState<Partial<Enterprise>>({});
  const [loading, setLoading] = useState(false);
  const [currentUser, setCurrentUser] = useState<any>(null);

  useEffect(() => {
    // 获取用户信息
    const userInfo = getAuthUser();
    console.log('🏢 从 Zustand 获取的用户信息:', userInfo);
    console.log('🏢 用户租户 ID (tenant_id):', userInfo?.tenant_id);

    if (!userInfo?.tenant_id) {
      toast.error('无法获取用户租户信息，请重新登录');
      return;
    }

    setCurrentUser(userInfo);

    // 加载企业信息
    loadEnterpriseInfo(userInfo.tenant_id);
  }, []);

  const loadEnterpriseInfo = async (tenantId: string) => {
    try {
      setLoading(true);
      console.log('🏢 开始加载企业信息，租户ID:', tenantId);

      // 调用API获取企业信息
      const enterpriseData = await fetchEnterpriseInfo(tenantId);

      if (enterpriseData) {
        setEnterprise(enterpriseData);
        setFormData(enterpriseData);
        console.log('🏢 企业信息加载成功:', enterpriseData);
      } else {
        console.log('🏢 企业信息为空，显示空状态');
        setEnterprise(null);
        setFormData({});
      }

    } catch (error) {
      console.error('🏢 加载企业信息失败:', error);
      const errorMessage = error instanceof Error ? error.message : '加载企业信息失败';
      toast.error(errorMessage);
      setEnterprise(null);
      setFormData({});
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleCancel = () => {
    setIsEditing(false);
    if (enterprise) {
      setFormData(enterprise);
    }
  };

  const handleSave = async () => {
    if (!currentUser?.tenant_id) {
      toast.error('无法获取用户租户信息，请重新登录');
      return;
    }

    // 验证必填字段
    if (!formData.name?.trim()) {
      toast.error('请填写企业名称');
      return;
    }

    try {
      setLoading(true);
      console.log('🏢 开始提交企业审核');

      // 构建提交审核的数据
      const submitData: SubmitAuditRequest = {
        company_name: formData.name || '',
        company_type: formData.type || null,
        province: formData.province || null,
        city: formData.city || null,
        district: formData.district || null,
        detailed_address: formData.address || null,
        registrant: formData.registrant || null,
        contact_phone: formData.contactPhone || null,
        bank_account: formData.bankAccount || null,
        bank_name: formData.bankName || null,
        bank_full_name: formData.bankFullName || null,
        bank_address: formData.bankAddress || null,
        bank_permit_image: null, // 暂时设为null，等待图片上传功能
        social_credit_code: formData.socialCreditCode || null,
        business_license_image: null, // 暂时设为null，等待图片上传功能
        legal_person_name: formData.legalPerson || null,
        id_card_front_image: null, // 暂时设为null，等待图片上传功能
        id_card_back_image: null, // 暂时设为null，等待图片上传功能
        company_scale: formData.companySize || null,
        registered_capital: formData.registeredCapital ? parseFloat(formData.registeredCapital.toString()) : null,
        established_date: formData.establishmentDate || null,
        invoice_type: formData.invoiceType || null,
        business_scope: formData.businessScope || null,
      };

      // 调用API提交审核
      await submitEnterpriseAudit(currentUser.tenant_id, submitData);

      // 提交成功，退出编辑模式
      setIsEditing(false);
      toast.success('企业信息已提交审核，请等待管理员审核');

      // 重新加载企业信息以获取最新状态
      await loadEnterpriseInfo(currentUser.tenant_id);

    } catch (error) {
      console.error('🏢 提交企业审核失败:', error);
      const errorMessage = error instanceof Error ? error.message : '提交审核失败';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (field: keyof Enterprise, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleImageUpload = (field: keyof Enterprise) => {
    // 图片上传功能需要对接后端服务
    toast.info('图片上传功能正在开发中');
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-green-800">企业信息</h2>
          <p className="text-muted-foreground">查看和管理本企业的完整注册信息</p>
        </div>
        <Card className="p-8 text-center text-muted-foreground">
          加载中...
        </Card>
      </div>
    );
  }

  if (!enterprise) {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-green-800">企业信息</h2>
          <p className="text-muted-foreground">查看和管理本企业的完整注册信息</p>
        </div>
        <Card className="p-8 text-center text-muted-foreground">
          {loading ? '加载中...' : '暂无企业信息或加载失败，请刷新页面重试'}
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <EnterpriseInfoHeader
        isEditing={isEditing}
        loading={loading}
        onEdit={handleEdit}
        onCancel={handleCancel}
        onSave={handleSave}
      />

      {/* 审核状态提示 */}
      <AuditStatusAlert enterprise={enterprise} />

      {/* 分标签页展示信息 */}
      <Tabs defaultValue="basic" className="space-y-4">
        <TabsList className="grid grid-cols-4 w-full max-w-2xl">
          <TabsTrigger value="basic">
            <Building className="w-4 h-4 mr-2" />
            基本信息
          </TabsTrigger>
          <TabsTrigger value="other">
            <FileText className="w-4 h-4 mr-2" />
            其他信息
          </TabsTrigger>
          <TabsTrigger value="bank">
            <CreditCard className="w-4 h-4 mr-2" />
            开户信息
          </TabsTrigger>
          <TabsTrigger value="legal">
            <User className="w-4 h-4 mr-2" />
            法人信息
          </TabsTrigger>
        </TabsList>

        {/* 企业基本信息 */}
        <TabsContent value="basic" className="space-y-4">
          <BasicInfoForm
            enterprise={enterprise}
            isEditing={isEditing}
            formData={formData}
            onFieldChange={handleChange}
          />
        </TabsContent>

        {/* 其他信息 */}
        <TabsContent value="other" className="space-y-4">
          <OtherInfoForm
            enterprise={enterprise}
            isEditing={isEditing}
            formData={formData}
            onFieldChange={handleChange}
            onImageUpload={handleImageUpload}
          />
        </TabsContent>

        {/* 开户信息 */}
        <TabsContent value="bank" className="space-y-4">
          <BankInfoForm
            enterprise={enterprise}
            isEditing={isEditing}
            formData={formData}
            onFieldChange={handleChange}
            onImageUpload={handleImageUpload}
          />
        </TabsContent>

        {/* 法人信息 */}
        <TabsContent value="legal" className="space-y-4">
          <LegalInfoForm
            enterprise={enterprise}
            isEditing={isEditing}
            formData={formData}
            onFieldChange={handleChange}
            onImageUpload={handleImageUpload}
          />
        </TabsContent>
      </Tabs>

      {/* 系统信息 */}
      <SystemInfo enterprise={enterprise} />

      {/* 操作提示 */}
      <OperationTips />
    </div>
  );
}