'use client';

import type React from 'react';

import { useState, useRef, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Upload, X, Loader2, FileText, AlertCircle, Download } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { toast } from '@/components/ui/use-toast';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from '@/components/ui/form';
import { Checkbox } from '@/components/ui/checkbox';
import { Combobox } from '@/components/ui/combobox';
import {
  provinces,
  positionOptions,
  databaseVersion,
  industryOptions,
  solutionTypeOptions,
  infrastructureCategory,
} from '@/lib/form-options';
import { ImageUpload } from '@/components/ui/image-upload';
import { getSMSCode, getApplicationDetail } from '@/lib/api/compatibility-certifications';
import { api } from '@/lib/api/base';

const MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB
const ACCEPTED_FILE_TYPES = [
  'application/msword', // .doc
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
];

const formSchema = z
  .object({
    company: z.string().min(1, { message: '请输入公司名称' }),
    company_address: z.string().min(1, { message: '请选择公司注册地' }),
    contact_name: z.string().min(1, { message: '请输入联系人姓名' }),
    contact_job_title: z.string().min(1, { message: '请选择联系人职位' }),
    contact_phone: z.string().regex(/^1[3-9]\d{9}$/, { message: '请输入正确的11位手机号码' }),
    phone_code: z.string().length(6, { message: '验证码必须为6位数字' }),
    contact_email: z
      .string()
      .regex(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, { message: '请输入联系人邮箱' }),
    product_name: z.string().min(1, { message: '请输入产品名称' }),
    product_description: z
      .string()
      .min(1, { message: '请输入产品简介' })
      .max(200, { message: '请输入产品简介 200 字以内' }),
    purpose_of_certification: z
      .string()
      .min(1, { message: '请输入认证用途' })
      .max(100, { message: '请输入认证用途 100 字以内' }),
    shipping_address: z.string().min(1, { message: '请输入证书邮寄地址' }),
    solution_type: z.string().min(1, { message: '请选择解决方案类型' }),
    infra_category: z.string().optional(),
    product_industry: z.string().min(1, { message: '请选择应用行业' }),
    compatible_database_version: z.string().min(1, { message: '请选择适配数据库版本' }),
    attachment_1: z
      .custom<File>((val) => val instanceof File, { message: '请上传测试报告' })
      .refine((file) => !file || file.size < MAX_FILE_SIZE, { message: '文件不能超过 20MB' })
      .refine((file) => !file || ACCEPTED_FILE_TYPES.includes(file.type), {
        message: '只支持 .doc 或 .docx 格式文件',
      }),
    company_logo: z
      .custom<File>((val) => val instanceof File, { message: '请上传公司 logo' })
      .refine((file) => !file || file.size <= 20 * 1024 * 1024, { message: '文件不能超过 20MB' }),
    cert_owner_name: z.string().min(1, { message: '请输入合作伙伴证书负责人姓名' }),
    cert_owner_job_title: z.string().min(1, { message: '请输入合作伙伴证书负责人职务' }),
    agreement: z.boolean().refine((val) => val === true, { message: '请同意协议' }),
  })
  .superRefine((values, ctx) => {
    if (values.solution_type === 'ke76LBbs7' && !values.infra_category) {
      ctx.addIssue({
        path: ['infra_category'],
        code: z.ZodIssueCode.custom,
        message: '请选择基础设施分类',
      });
    }
  });

type FormValues = z.infer<typeof formSchema>;

export function ApplicationForm() {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const router = useRouter();
  const searchParams = useSearchParams();
  const [showSuccessDialog, setShowSuccessDialog] = useState(false);
  const [showErrorDialog, setShowErrorDialog] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [codeSent, setCodeSent] = useState(false);
  const [countdown, setCountdown] = useState(60);
  const countdownRef = useRef<NodeJS.Timeout | null>(null);
  const [isResubmission, setIsResubmission] = useState(false);
  const [rejectionReason, setRejectionReason] = useState('');
  const [isLoadingApplication, setIsLoadingApplication] = useState(false);

  const [attachment_1, setTestReportFile] = useState<File | null>(null);
  const testFileInputRef = useRef<HTMLInputElement>(null);

  const urlToFile = async (url: string, filename: string): Promise<File> => {
    const response = await fetch(process.env.NEXT_PUBLIC_API_BASE_URL + url);
    const blob = await response.blob();
    return new File([blob], filename, { type: blob.type });
  };

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      company: '',
      company_address: '',
      contact_name: '',
      contact_job_title: '',
      contact_phone: '',
      phone_code: '',
      contact_email: '',
      product_name: '',
      product_description: '',
      purpose_of_certification: '',
      shipping_address: '',
      solution_type: '',
      product_industry: '',
      compatible_database_version: '',
      cert_owner_name: '',
      cert_owner_job_title: '',
      agreement: false,
      attachment_1: undefined,
      company_logo: undefined,
      infra_category: '',
    },
  });

  useEffect(() => {
    const resubmitId = searchParams.get('resubmit');

    if (resubmitId) {
      setIsResubmission(true);
      setIsLoadingApplication(true);

      getApplicationDetail(resubmitId)
        .then(async (applicationData) => {
          const appData = Array.isArray(applicationData.data)
            ? applicationData.data[0]
            : applicationData.data;

          const logoFile = await urlToFile(appData.company_logo, 'company-logo.png');

          const attachmentFile = await urlToFile(appData.attachment_1, 'attachment_1.doc');
          setTestReportFile(attachmentFile);

          form.reset({
            ...appData,
            phone_code: '',
            infra_category: appData.infra_category ?? '',
            attachment_1: attachmentFile,
            company_logo: logoFile,
            agreement: false,
          });

          if (appData.staff_comment) {
            setRejectionReason(appData.staff_comment);
          }

          toast({
            title: '已加载申请数据',
            description: '您的申请数据已自动填充，请修改后重新提交。',
          });
        })
        .catch((error) => {
          console.error('Failed to load application data:', error);
          toast({
            title: '加载失败',
            description: '无法加载申请数据，请重新填写表单。',
            variant: 'destructive',
          });
        })
        .finally(() => {
          setIsLoadingApplication(false);
        });
    }
  }, [searchParams, form]);

  const handleSendCode = async () => {
    const phoneValue = form.getValues('contact_phone');
    const phoneRegex = /^1[3-9]\d{9}$/;

    if (!phoneValue || !phoneRegex.test(phoneValue)) {
      form.setError('contact_phone', {
        type: 'manual',
        message: '请输入正确的11位手机号码',
      });
      return;
    }

    if (countdownRef.current) {
      clearInterval(countdownRef.current);
    }

    setCodeSent(true);
    setCountdown(60);
    countdownRef.current = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(countdownRef.current!);
          setCodeSent(false);
          return 60;
        }
        return prev - 1;
      });
    }, 1000);

    try {
      const response = await getSMSCode(phoneValue);

      if (response.detail === 'success') {
        toast({
          title: '验证码已发送',
          description: `验证码已发送至 ${phoneValue}，请注意查收`,
        });
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.errors?.phone?.[0] || '发送验证码失败，请稍后重试';
      toast({
        title: '发送失败',
        description: errorMessage,
        variant: 'destructive',
      });
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>, fileType: 'attachment_1') => {
    const file = e.target.files?.[0];

    if (file) {
      setTestReportFile(file);
      form.setValue('attachment_1', file);
      form.clearErrors('attachment_1');
    }
  };

  const handleRemoveFile = (fileType: 'attachment_1') => {
    setTestReportFile(null);
    form.setValue('attachment_1', undefined as unknown as File);
    if (testFileInputRef.current) {
      testFileInputRef.current.value = '';
    }
  };

  const handleLogoChange = (file: File | undefined) => {
    form.setValue('company_logo', file as any);
    form.clearErrors('company_logo');
  };

  const onSubmit = async (data: FormValues) => {
    setIsSubmitting(true);

    try {
      await api.post('/api/partner/compatibility-certifications/applications', data, {
        isMultipart: true,
      });

      setShowSuccessDialog(true);
      setIsSubmitting(false);
    } catch (err: any) {
      setIsSubmitting(false);
      if (err.errors) {
        setErrorMessage(`提交失败，${err.errors[Object.keys(err.errors)[0]]}`);
        setShowErrorDialog(true);
      }
    }
  };

  const handleSuccessClose = () => {
    setShowSuccessDialog(false);
    router.push('/dashboard/applications/records');
  };

  return (
    <div className="space-y-6">
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          encType="multipart/form-data"
          className="space-y-8"
        >
          <div className="mb-6 rounded-md bg-blue-50 p-4 text-sm text-gray-700">
            <p>
              请严格按照适配证书填写申请信息，申请信息必须真实有效。"*"表示必填项目，提交申请前请确认信息准确无误。
            </p>
          </div>

          {isResubmission && rejectionReason && (
            <div className="mb-6 rounded-md bg-yellow-50 border border-yellow-200 p-4 text-sm">
              <h4 className="font-medium text-yellow-800 mb-1">申请驳回原因：</h4>
              <p className="text-yellow-700">{rejectionReason}</p>
            </div>
          )}

          {isLoadingApplication && (
            <div className="mb-6 rounded-md bg-blue-50 p-4 text-sm text-blue-700">
              <div className="flex items-center">
                <Loader2 className="h-4 w-4 animate-spin mr-2" />
                正在加载申请数据...
              </div>
            </div>
          )}

          <div className="space-y-6">
            <h3 className="text-lg font-medium border-l-4 border-blue-600 pl-2">基本信息</h3>

            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              <FormField
                control={form.control}
                name="company"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      公司名称 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input placeholder="请输入公司全称" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="company_address"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      公司注册地 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Combobox
                        options={provinces}
                        value={field.value}
                        onValueChange={field.onChange}
                        placeholder="请选择省份"
                        searchPlaceholder="搜索省份..."
                        emptyMessage="未找到匹配的省份"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contact_name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      联系人姓名 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input placeholder="请输入联系人姓名" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contact_job_title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      联系人职位 <span className="text-red-500">*</span>
                    </FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="请选择职位" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {positionOptions.map((item) => (
                          <SelectItem key={item.value} value={item.value}>
                            {item.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contact_phone"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      手机号码 <span className="text-red-500">*</span>
                    </FormLabel>
                    <div className="flex gap-2">
                      <FormControl>
                        <Input placeholder="请输入11位手机号码" {...field} />
                      </FormControl>
                      <Button
                        type="button"
                        variant="outline"
                        onClick={handleSendCode}
                        disabled={codeSent || !field.value || !/^1[3-9]\d{9}$/.test(field.value)}
                      >
                        {codeSent ? `${countdown}秒后重发` : '发送验证码'}
                      </Button>
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="phone_code"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      验证码 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input placeholder="请输入6位验证码" maxLength={6} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contact_email"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>
                      联系人邮箱 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input placeholder="请输入邮箱" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <h3 className="text-lg font-medium border-l-4 border-blue-600 pl-2 mt-8">产品信息</h3>

            <FormField
              control={form.control}
              name="product_name"
              render={({ field }) => (
                <FormItem className="md:col-span-2">
                  <FormLabel>
                    产品名称 <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input placeholder="请输入产品名称，将展示在互认证证书中" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="space-y-4">
              <FormField
                control={form.control}
                name="product_description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      产品简介 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="请输入产品简介，将展示在互认证证书中，建议 200 字以内"
                        rows={4}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="product_industry"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      应用行业 <span className="text-red-500">*</span>
                    </FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                      value={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="请选择应用行业" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {industryOptions.map((item) => (
                          <SelectItem key={item.value} value={item.value}>
                            {item.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="purpose_of_certification"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      认证用途 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="请描述本次适配的背景，如：技术适配储备、具体项目需要，如有具体项目需要请描述项目的所属地和对应行业，建议 100 字以内"
                        rows={4}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <h3 className="text-lg font-medium border-l-4 border-blue-600 pl-2 mt-8">适配信息</h3>

            <div className="space-y-4">
              <FormField
                control={form.control}
                name="compatible_database_version"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      适配数据库版本 <span className="text-red-500">*</span>
                    </FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                      value={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="请选择适配数据库版本" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {databaseVersion.map((item) => (
                          <SelectItem key={item.value} value={item.value}>
                            {item.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="solution_type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      适配方案类型 <span className="text-red-500">*</span>
                    </FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                      value={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="请选择适配方案类型" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {solutionTypeOptions.map((item) => (
                          <SelectItem value={item.value} key={item.value}>
                            {item.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {form.watch('solution_type') === 'ke76LBbs7' && (
                <FormField
                  control={form.control}
                  name="infra_category"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        基础设施分类 <span className="text-red-500">*</span>
                      </FormLabel>
                      <Select
                        onValueChange={field.onChange}
                        defaultValue={field.value}
                        value={field.value}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="请选择基础设施分类" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {infrastructureCategory.map((item) => (
                            <SelectItem value={item.value} key={item.value}>
                              {item.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}

              <FormField
                control={form.control}
                name="attachment_1"
                render={() => (
                  <FormItem>
                    <FormLabel className="flex">
                      测试报告上传 <span className="text-red-500 pr-4">*</span>
                      <a
                        className="flex items-center gap-1 text-xs text-primary hover:underline"
                        href="https://img1.pingcap.com/files/2025/06/%E4%BA%92%E8%AE%A4%E8%AF%81%E9%80%82%E9%85%8D%E6%8A%A5%E5%91%8A%E6%A8%A1%E6%9D%BF.zip"
                      >
                        <Download className="h-3 w-3" />
                        互认证适配报告模板下载
                      </a>
                    </FormLabel>
                    <FormControl>
                      <div>
                        <div className="border-2 border-dashed rounded-md p-6 flex flex-col items-center justify-center">
                          <Input
                            type="file"
                            id="attachment_1"
                            accept={ACCEPTED_FILE_TYPES.join(',')}
                            onChange={(e) => handleFileChange(e, 'attachment_1')}
                            className="hidden"
                          />
                          <label htmlFor="attachment_1" className="cursor-pointer w-full h-full">
                            <div className="flex flex-col items-center justify-center gap-2">
                              <div className="rounded-full bg-gray-100 p-2">
                                <Upload className="h-6 w-6 text-gray-500" />
                              </div>
                              <p className="text-sm text-gray-500">点击或拖拽文件到此处上传</p>
                              <p className="text-xs text-gray-400">
                                仅支持 .doc 或 .docx 格式文件，文件大小不超过 20MB
                              </p>
                            </div>
                          </label>
                        </div>
                        {attachment_1 && (
                          <div className="space-y-2">
                            <Label>已上传文件</Label>
                            <div className="rounded-md border p-3">
                              <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                  <FileText className="h-5 w-5 text-gray-500" />
                                  <span className="text-sm">{attachment_1.name}</span>
                                </div>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-8 w-8 p-0"
                                  onClick={() => handleRemoveFile('attachment_1')}
                                  type="button"
                                >
                                  <X className="h-4 w-4" />
                                </Button>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="company_logo"
                render={({ field: { value, onChange, ...field } }) => (
                  <FormItem>
                    <FormLabel>
                      公司 logo 上传 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <ImageUpload
                        value={value}
                        onChange={handleLogoChange}
                        onError={(error) => {
                          form.setError('company_logo', { message: error });
                        }}
                      />
                    </FormControl>
                    <FormDescription>
                      请上传公司 logo，背景色需透明，仅支持.png 格式文件，文件大小不超过 20MB
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="cert_owner_name"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>
                      合作伙伴证书负责人姓名 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input placeholder="请输入合作伙伴证书负责人姓名" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="cert_owner_job_title"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>
                      合作伙伴证书负责人职务 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input placeholder="请输入合作伙伴证书负责人职务" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="shipping_address"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>
                      证书邮寄地址 <span className="text-red-500">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input placeholder="请输入证书邮寄地址" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="agreement"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0 mt-4">
                    <FormControl>
                      <Checkbox checked={field.value} onCheckedChange={field.onChange} />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel className="text-sm">
                        请阅读并同意{' '}
                        <a
                          href="https://pingkai.cn/legal/privacy-policy"
                          target="_blank"
                          className="text-primary hover:underline"
                        >
                          平凯星辰隐私政策
                        </a>
                      </FormLabel>
                      <FormMessage />
                    </div>
                  </FormItem>
                )}
              />
            </div>
          </div>

          <div className="flex justify-center">
            <Button type="submit" size="lg" disabled={isSubmitting || isLoadingApplication}>
              {isSubmitting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  提交中...
                </>
              ) : isResubmission ? (
                '重新提交申请'
              ) : (
                '提交申请'
              )}
            </Button>
          </div>
        </form>
      </Form>

      <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-center">申请提交成功</DialogTitle>
          </DialogHeader>
          <div className="flex flex-col items-center justify-center py-6">
            <div className="rounded-full bg-green-100 p-3 mb-4">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="h-6 w-6 text-green-600"
              >
                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                <polyline points="22 4 12 14.01 9 11.01"></polyline>
              </svg>
            </div>
            <p className="text-center mb-2">您的适配认证申请已成功提交</p>
            <p className="text-sm text-gray-500 text-center mt-2">
              我们将在3个工作日内审核您的申请，请留意申请状态变化
            </p>
          </div>
          <DialogFooter>
            <Button onClick={handleSuccessClose} className="w-full">
              查看申请列表
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showErrorDialog} onOpenChange={setShowErrorDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-center">提交失败</DialogTitle>
          </DialogHeader>
          <div className="flex flex-col items-center justify-center py-6">
            <div className="rounded-full bg-red-100 p-3 mb-4">
              <AlertCircle className="h-6 w-6 text-red-600" />
            </div>
            <p className="text-center mb-4">{errorMessage}</p>
          </div>
          <DialogFooter className="flex flex-col sm:flex-row gap-2">
            <Button
              variant="outline"
              onClick={() => setShowErrorDialog(false)}
              className="sm:flex-1"
            >
              返回编辑
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
