import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Label } from '../ui/label';
import { Switch } from '../ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { SystemSettings as SystemSettingsType } from '../../types/system-params';
import { Settings, Save, RefreshCw, Info, Shield, Globe } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function SystemSettings() {
  const [settings, setSettings] = useState<SystemSettingsType>({
    platformName: '智慧农业生产管理系统',
    platformLogo: '',
    systemAnnouncement: '欢迎使用智慧农业生产管理系统！',
    contactEmail: 'support@smart-agriculture.com',
    contactPhone: '400-888-8888',
    address: '北京市海淀区中关村大街1号',
    companyName: '智慧农业科技有限公司',
    icp: '京ICP备12345678号',
    copyright: '© 2024 智慧农业科技有限公司 版权所有',
    enableRegistration: true,
    enableGuestAccess: false,
    sessionTimeout: 30,
    maxLoginAttempts: 5,
    passwordPolicy: {
      minLength: 8,
      requireUppercase: true,
      requireLowercase: true,
      requireNumbers: true,
      requireSpecialChars: false,
    },
    dateFormat: 'YYYY-MM-DD',
    timezone: 'Asia/Shanghai',
    language: 'zh-CN',
  });

  const [hasChanges, setHasChanges] = useState(false);

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = () => {
    const data = localStorage.getItem('smart_agriculture_system_settings');
    if (data) {
      setSettings(JSON.parse(data));
    } else {
      saveSettings(settings);
    }
  };

  const saveSettings = (newSettings: SystemSettingsType) => {
    localStorage.setItem('smart_agriculture_system_settings', JSON.stringify(newSettings));
    setSettings(newSettings);
    setHasChanges(false);
    toast.success('系统设置已保存');
  };

  const handleSave = () => {
    saveSettings(settings);
  };

  const handleReset = () => {
    loadSettings();
    setHasChanges(false);
    toast.info('已恢复到上次保存的设置');
  };

  const updateSettings = (updates: Partial<SystemSettingsType>) => {
    setSettings({ ...settings, ...updates });
    setHasChanges(true);
  };

  const updatePasswordPolicy = (updates: Partial<SystemSettingsType['passwordPolicy']>) => {
    setSettings({
      ...settings,
      passwordPolicy: { ...settings.passwordPolicy, ...updates }
    });
    setHasChanges(true);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">系统设置</h2>
          <p className="text-muted-foreground">配置系统全局基础参数和个性化设置</p>
        </div>
        <div className="flex gap-2">
          {hasChanges && (
            <Button variant="outline" onClick={handleReset}>
              <RefreshCw className="w-4 h-4 mr-2" />
              重置
            </Button>
          )}
          <Button onClick={handleSave} disabled={!hasChanges}>
            <Save className="w-4 h-4 mr-2" />
            保存设置
          </Button>
        </div>
      </div>

      <Tabs defaultValue="basic" className="space-y-4">
        <TabsList>
          <TabsTrigger value="basic">
            <Info className="w-4 h-4 mr-2" />
            基本设置
          </TabsTrigger>
          <TabsTrigger value="security">
            <Shield className="w-4 h-4 mr-2" />
            安全设置
          </TabsTrigger>
          <TabsTrigger value="regional">
            <Globe className="w-4 h-4 mr-2" />
            区域设置
          </TabsTrigger>
        </TabsList>

        {/* 基本设置 */}
        <TabsContent value="basic" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">平台信息</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>平台名称 *</Label>
                <Input
                  value={settings.platformName}
                  onChange={(e) => updateSettings({ platformName: e.target.value })}
                  placeholder="请输入平台名称"
                />
              </div>
              <div>
                <Label>公司名称</Label>
                <Input
                  value={settings.companyName}
                  onChange={(e) => updateSettings({ companyName: e.target.value })}
                  placeholder="请输入公司名称"
                />
              </div>
              <div>
                <Label>联系邮箱</Label>
                <Input
                  type="email"
                  value={settings.contactEmail}
                  onChange={(e) => updateSettings({ contactEmail: e.target.value })}
                  placeholder="support@example.com"
                />
              </div>
              <div>
                <Label>联系电话</Label>
                <Input
                  value={settings.contactPhone}
                  onChange={(e) => updateSettings({ contactPhone: e.target.value })}
                  placeholder="400-888-8888"
                />
              </div>
              <div className="md:col-span-2">
                <Label>公司地址</Label>
                <Input
                  value={settings.address}
                  onChange={(e) => updateSettings({ address: e.target.value })}
                  placeholder="请输入公司地址"
                />
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <h3 className="mb-4">系统公告</h3>
            <Textarea
              value={settings.systemAnnouncement}
              onChange={(e) => updateSettings({ systemAnnouncement: e.target.value })}
              placeholder="输入系统公告内容，将显示在登录页面"
              rows={4}
            />
          </Card>

          <Card className="p-6">
            <h3 className="mb-4">版权信息</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>ICP备案号</Label>
                <Input
                  value={settings.icp}
                  onChange={(e) => updateSettings({ icp: e.target.value })}
                  placeholder="京ICP备12345678号"
                />
              </div>
              <div>
                <Label>版权声明</Label>
                <Input
                  value={settings.copyright}
                  onChange={(e) => updateSettings({ copyright: e.target.value })}
                  placeholder="© 2024 公司名称 版权所有"
                />
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <h3 className="mb-4">功能开关</h3>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <Label>允许用户注册</Label>
                  <p className="text-sm text-muted-foreground">开启后允许新用户自主注册账号</p>
                </div>
                <Switch
                  checked={settings.enableRegistration}
                  onCheckedChange={(checked) => updateSettings({ enableRegistration: checked })}
                />
              </div>
              <div className="flex items-center justify-between">
                <div>
                  <Label>允许访客访问</Label>
                  <p className="text-sm text-muted-foreground">开启后允许未登录用户访问部分公开内容</p>
                </div>
                <Switch
                  checked={settings.enableGuestAccess}
                  onCheckedChange={(checked) => updateSettings({ enableGuestAccess: checked })}
                />
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 安全设置 */}
        <TabsContent value="security" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">会话管理</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>会话超时时间（分钟）</Label>
                <Input
                  type="number"
                  value={settings.sessionTimeout}
                  onChange={(e) => updateSettings({ sessionTimeout: parseInt(e.target.value) || 30 })}
                  min={5}
                  max={1440}
                />
                <p className="text-sm text-muted-foreground mt-1">
                  用户无操作超过此时间后将自动退出登录
                </p>
              </div>
              <div>
                <Label>最大登录尝试次数</Label>
                <Input
                  type="number"
                  value={settings.maxLoginAttempts}
                  onChange={(e) => updateSettings({ maxLoginAttempts: parseInt(e.target.value) || 5 })}
                  min={3}
                  max={10}
                />
                <p className="text-sm text-muted-foreground mt-1">
                  连续登录失败达到此次数后账号将被临时锁定
                </p>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <h3 className="mb-4">密码策略</h3>
            <div className="space-y-4">
              <div>
                <Label>最小密码长度</Label>
                <Input
                  type="number"
                  value={settings.passwordPolicy.minLength}
                  onChange={(e) => updatePasswordPolicy({ minLength: parseInt(e.target.value) || 8 })}
                  min={6}
                  max={32}
                />
              </div>
              <div className="space-y-3">
                <Label>密码复杂度要求</Label>
                <div className="flex items-center justify-between">
                  <span className="text-sm">要求包含大写字母</span>
                  <Switch
                    checked={settings.passwordPolicy.requireUppercase}
                    onCheckedChange={(checked) => updatePasswordPolicy({ requireUppercase: checked })}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm">要求包含小写字母</span>
                  <Switch
                    checked={settings.passwordPolicy.requireLowercase}
                    onCheckedChange={(checked) => updatePasswordPolicy({ requireLowercase: checked })}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm">要求包含数字</span>
                  <Switch
                    checked={settings.passwordPolicy.requireNumbers}
                    onCheckedChange={(checked) => updatePasswordPolicy({ requireNumbers: checked })}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm">要求包含特殊字符</span>
                  <Switch
                    checked={settings.passwordPolicy.requireSpecialChars}
                    onCheckedChange={(checked) => updatePasswordPolicy({ requireSpecialChars: checked })}
                  />
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 区域设置 */}
        <TabsContent value="regional" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">区域与语言</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>语言</Label>
                <Select
                  value={settings.language}
                  onValueChange={(value) => updateSettings({ language: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="zh-CN">简体中文</SelectItem>
                    <SelectItem value="zh-TW">繁體中文</SelectItem>
                    <SelectItem value="en-US">English</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>时区</Label>
                <Select
                  value={settings.timezone}
                  onValueChange={(value) => updateSettings({ timezone: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Asia/Shanghai">中国标准时间 (UTC+8)</SelectItem>
                    <SelectItem value="Asia/Tokyo">日本标准时间 (UTC+9)</SelectItem>
                    <SelectItem value="America/New_York">美国东部时间 (UTC-5)</SelectItem>
                    <SelectItem value="Europe/London">格林威治标准时间 (UTC+0)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>日期格式</Label>
                <Select
                  value={settings.dateFormat}
                  onValueChange={(value) => updateSettings({ dateFormat: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="YYYY-MM-DD">2024-10-14</SelectItem>
                    <SelectItem value="DD/MM/YYYY">14/10/2024</SelectItem>
                    <SelectItem value="MM/DD/YYYY">10/14/2024</SelectItem>
                    <SelectItem value="YYYY年MM月DD日">2024年10月14日</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 设置预览 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <Settings className="w-4 h-4 inline mr-2" />
          设置说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 平台名称和Logo将显示在系统导航栏和登录页面</li>
          <li>• 系统公告会在登录后首页显著位置展示</li>
          <li>• 密码策略设置将在用户创建或修改密码时生效</li>
          <li>• 会话超时设置可提高系统安全性，防止账号被盗用</li>
          <li>• 修改设置后需要点击"保存设置"按钮才会生效</li>
        </ul>
      </Card>
    </div>
  );
}
