import React from 'react';
import { useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Switch } from '@d8d/shared-ui-components/components/ui/switch';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { tenantClient } from '@/api/tenantClient';
import { useTenantConfig } from '@/hooks/useTenantConfig';

interface TenantConfigFormData {
  theme: string;
  language: string;
  timezone: string;
  currency: string;
  maxUsers: number;
  maxStorage: number;
  enableNotifications: boolean;
  enableAuditLog: boolean;
  customSettings: string;
}

export const TenantConfigPage = () => {
  const { id } = useParams<{ id: string }>();
  const tenantId = parseInt(id || '0');

  const { data: tenant, isLoading: isTenantLoading } = useQuery({
    queryKey: ['tenant', tenantId],
    queryFn: async () => {
      const res = await tenantClient[':id'].$get({
        param: { id: tenantId }
      });
      if (res.status !== 200) {
        throw new Error('获取租户信息失败');
      }
      return await res.json();
    },
    enabled: !!tenantId
  });

  const { data: config, isLoading: isConfigLoading, updateConfig, isUpdating } = useTenantConfig(tenantId);

  const form = useForm<TenantConfigFormData>({
    defaultValues: {
      theme: 'light',
      language: 'zh-CN',
      timezone: 'Asia/Shanghai',
      currency: 'CNY',
      maxUsers: 100,
      maxStorage: 1024,
      enableNotifications: true,
      enableAuditLog: true,
      customSettings: '{}'
    }
  });

  React.useEffect(() => {
    if (config) {
      form.reset({
        theme: config.theme || 'light',
        language: config.language || 'zh-CN',
        timezone: config.timezone || 'Asia/Shanghai',
        currency: config.currency || 'CNY',
        maxUsers: config.maxUsers || 100,
        maxStorage: config.maxStorage || 1024,
        enableNotifications: config.enableNotifications !== false,
        enableAuditLog: config.enableAuditLog !== false,
        customSettings: typeof config.customSettings === 'string'
          ? config.customSettings
          : JSON.stringify(config.customSettings || {}, null, 2)
      });
    }
  }, [config, form]);

  const onSubmit = async (data: TenantConfigFormData) => {
    try {
      const configData = {
        theme: data.theme,
        language: data.language,
        timezone: data.timezone,
        currency: data.currency,
        maxUsers: data.maxUsers,
        maxStorage: data.maxStorage,
        enableNotifications: data.enableNotifications,
        enableAuditLog: data.enableAuditLog,
        customSettings: JSON.parse(data.customSettings)
      };

      await updateConfig(configData);
    } catch {
      toast.error('保存配置失败');
    }
  };

  if (isTenantLoading || isConfigLoading) {
    return (
      <div className="space-y-4">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded w-1/4 mb-4"></div>
          <div className="space-y-3">
            <div className="h-4 bg-gray-200 rounded w-3/4"></div>
            <div className="h-4 bg-gray-200 rounded w-1/2"></div>
          </div>
        </div>
      </div>
    );
  }

  if (!tenant) {
    return (
      <div className="text-center py-8">
        <h2 className="text-xl font-semibold text-gray-600">租户不存在</h2>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">租户配置管理</h1>
        <p className="text-gray-600 mt-2">
          管理租户 "{tenant.name || tenant.code}" 的系统配置
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>基本配置</CardTitle>
          <CardDescription>
            配置租户的基本系统设置
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* 主题设置 */}
              <div className="space-y-2">
                <Label htmlFor="theme">主题</Label>
                <Select
                  value={form.watch('theme')}
                  onValueChange={(value: string) => form.setValue('theme', value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择主题" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="light">浅色</SelectItem>
                    <SelectItem value="dark">深色</SelectItem>
                    <SelectItem value="auto">自动</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 语言设置 */}
              <div className="space-y-2">
                <Label htmlFor="language">语言</Label>
                <Select
                  value={form.watch('language')}
                  onValueChange={(value: string) => form.setValue('language', value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择语言" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="zh-CN">简体中文</SelectItem>
                    <SelectItem value="en-US">English</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 时区设置 */}
              <div className="space-y-2">
                <Label htmlFor="timezone">时区</Label>
                <Select
                  value={form.watch('timezone')}
                  onValueChange={(value: string) => form.setValue('timezone', value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择时区" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Asia/Shanghai">上海 (UTC+8)</SelectItem>
                    <SelectItem value="America/New_York">纽约 (UTC-5)</SelectItem>
                    <SelectItem value="Europe/London">伦敦 (UTC+0)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 货币设置 */}
              <div className="space-y-2">
                <Label htmlFor="currency">货币</Label>
                <Select
                  value={form.watch('currency')}
                  onValueChange={(value: string) => form.setValue('currency', value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择货币" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="CNY">人民币 (CNY)</SelectItem>
                    <SelectItem value="USD">美元 (USD)</SelectItem>
                    <SelectItem value="EUR">欧元 (EUR)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 最大用户数 */}
              <div className="space-y-2">
                <Label htmlFor="maxUsers">最大用户数</Label>
                <Input
                  id="maxUsers"
                  type="number"
                  min="1"
                  max="10000"
                  {...form.register('maxUsers', { valueAsNumber: true })}
                />
              </div>

              {/* 最大存储空间 */}
              <div className="space-y-2">
                <Label htmlFor="maxStorage">最大存储空间 (MB)</Label>
                <Input
                  id="maxStorage"
                  type="number"
                  min="1"
                  max="1048576"
                  {...form.register('maxStorage', { valueAsNumber: true })}
                />
              </div>
            </div>

            {/* 功能开关 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label htmlFor="enableNotifications">启用通知</Label>
                  <p className="text-sm text-gray-500">
                    启用系统通知功能
                  </p>
                </div>
                <Switch
                  id="enableNotifications"
                  checked={form.watch('enableNotifications')}
                  onCheckedChange={(checked: boolean) => form.setValue('enableNotifications', checked)}
                />
              </div>

              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label htmlFor="enableAuditLog">启用审计日志</Label>
                  <p className="text-sm text-gray-500">
                    记录系统操作日志
                  </p>
                </div>
                <Switch
                  id="enableAuditLog"
                  checked={form.watch('enableAuditLog')}
                  onCheckedChange={(checked: boolean) => form.setValue('enableAuditLog', checked)}
                />
              </div>
            </div>

            {/* 自定义设置 */}
            <div className="space-y-2">
              <Label htmlFor="customSettings">自定义设置</Label>
              <Textarea
                id="customSettings"
                placeholder='{"key": "value"}'
                rows={6}
                {...form.register('customSettings')}
              />
              <p className="text-sm text-gray-500">
                请输入有效的JSON格式配置
              </p>
            </div>

            <div className="flex justify-end">
              <Button type="submit" disabled={isUpdating}>
                {isUpdating ? '保存中...' : '保存配置'}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
};