import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { CreateTenantDto, UpdateTenantDto } from '@d8d/tenant-module-mt/schemas';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { Switch } from '@d8d/shared-ui-components/components/ui/switch';
import type { InferResponseType } from 'hono/client';
import type { tenantClient } from '../api/tenantClient';

type TenantResponse = InferResponseType<typeof tenantClient.index.$get, 200>['data'][0];

interface TenantFormProps {
  tenant?: TenantResponse;
  onSubmit: (data: Record<string, unknown>) => Promise<void>;
  onCancel: () => void;
  isSubmitting?: boolean;
}

export const TenantForm: React.FC<TenantFormProps> = ({
  tenant,
  onSubmit,
  onCancel,
  isSubmitting = false
}) => {
  const isEditing = !!tenant;

  const form = useForm({
    resolver: zodResolver(isEditing ? UpdateTenantDto : CreateTenantDto),
    defaultValues: {
      name: tenant?.name || '',
      code: tenant?.code || '',
      contactName: tenant?.contactName || '',
      phone: tenant?.phone || '',
      status: tenant?.status || 1,
      config: tenant?.config || null,
      rsaPublicKey: tenant?.rsaPublicKey || '',
      aesKey: tenant?.aesKey || '',
    },
  });

  const handleSubmit = async (data: Record<string, unknown>) => {
    // 过滤空值
    const submitData = Object.fromEntries(
      Object.entries(data).filter(([, value]) => {
        if (value === '' || value === null) return false;
        if (typeof value === 'string' && value.trim() === '') return false;
        return true;
      })
    );

    await onSubmit(submitData);
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>租户名称</FormLabel>
              <FormControl>
                <Input placeholder="请输入租户名称" {...field} />
              </FormControl>
              <FormDescription>
                租户的显示名称
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="code"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="flex items-center">
                租户代码
                <span className="text-red-500 ml-1">*</span>
              </FormLabel>
              <FormControl>
                <Input
                  placeholder="请输入租户代码"
                  {...field}
                  disabled={isEditing}
                />
              </FormControl>
              <FormDescription>
                租户的唯一标识符，创建后不可修改
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="contactName"
          render={({ field }) => (
            <FormItem>
              <FormLabel>联系人姓名</FormLabel>
              <FormControl>
                <Input placeholder="请输入联系人姓名" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="phone"
          render={({ field }) => (
            <FormItem>
              <FormLabel>联系电话</FormLabel>
              <FormControl>
                <Input placeholder="请输入联系电话" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="status"
          render={({ field }) => (
            <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
              <div className="space-y-0.5">
                <FormLabel className="text-base">租户状态</FormLabel>
                <FormDescription>
                  禁用后租户将无法使用系统
                </FormDescription>
              </div>
              <FormControl>
                <Switch
                  checked={field.value === 1}
                  onCheckedChange={(checked) => field.onChange(checked ? 1 : 2)}
                />
              </FormControl>
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="rsaPublicKey"
          render={({ field }) => (
            <FormItem>
              <FormLabel>RSA公钥</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="请输入RSA公钥"
                  rows={4}
                  {...field}
                />
              </FormControl>
              <FormDescription>
                用于加密通信的RSA公钥
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="aesKey"
          render={({ field }) => (
            <FormItem>
              <FormLabel>AES密钥</FormLabel>
              <FormControl>
                <Input
                  placeholder="请输入AES密钥"
                  {...field}
                />
              </FormControl>
              <FormDescription>
                用于数据加密的AES密钥（32位字符）
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="flex justify-end gap-2 pt-4">
          <Button type="button" variant="outline" onClick={onCancel}>
            取消
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting ? '提交中...' : (isEditing ? '更新租户' : '创建租户')}
          </Button>
        </div>
      </form>
    </Form>
  );
};