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 { 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, Palette } from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { useTheme } from '../ThemeProvider';

export function SystemSettings() {
  const { setTheme } = useTheme();
  const [settings, setSettings] = useState<SystemSettingsType>({
    platformName: '智慧农业生产管理系统',
    platformLogo: '',
    systemAnnouncement: '欢迎使用智慧农业生产管理系统！',
    contactEmail: 'support@smart-agriculture.com',
    contactPhone: '400-888-8888',
    address: '北京市海淀区中关村大街1号',
    defaultTheme: 'light',
  });

  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);
    
    // 应用默认主题设置
    setTheme(newSettings.defaultTheme);
    
    toast.success('系统设置已保存');
  };

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

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

  const updateSettings = (updates: Partial<SystemSettingsType>) => {
    setSettings({ ...settings, ...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="appearance">
            <Palette 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="请输入平台名称"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  平台名称将显示在系统导航栏和登录页面
                </p>
              </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>
                <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}
            />
            <p className="text-xs text-muted-foreground mt-2">
              系统公告会在登录页面显著位置展示
            </p>
          </Card>
        </TabsContent>

        {/* 外观设置 */}
        <TabsContent value="appearance" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">主题设置</h3>
            <div className="space-y-4">
              <div>
                <Label>默认主题</Label>
                <Select
                  value={settings.defaultTheme}
                  onValueChange={(value: 'light' | 'dark') => updateSettings({ defaultTheme: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="light">
                      <div className="flex items-center gap-2">
                        <div className="w-4 h-4 rounded-full bg-white border-2 border-gray-300" />
                        <span>明亮模式</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="dark">
                      <div className="flex items-center gap-2">
                        <div className="w-4 h-4 rounded-full bg-gray-900 border-2 border-gray-600" />
                        <span>暗黑模式</span>
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground mt-2">
                  设置系统默认主题，保存后立即生效。用户可以在导航栏手动切换主题。
                </p>
              </div>
            </div>
          </Card>

          <Card className="p-6 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900">
            <h4 className="text-blue-900 dark:text-blue-400 mb-2">
              <Palette className="w-4 h-4 inline mr-2" />
              主题预览
            </h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 rounded-lg bg-white border-2 border-gray-300">
                <p className="text-sm mb-2">明亮模式</p>
                <div className="space-y-2">
                  <div className="h-2 bg-green-600 rounded" />
                  <div className="h-2 bg-gray-200 rounded" />
                  <div className="h-2 bg-gray-200 rounded w-3/4" />
                </div>
              </div>
              <div className="p-4 rounded-lg bg-gray-900 border-2 border-gray-600">
                <p className="text-sm text-white mb-2">暗黑模式</p>
                <div className="space-y-2">
                  <div className="h-2 bg-green-500 rounded" />
                  <div className="h-2 bg-gray-700 rounded" />
                  <div className="h-2 bg-gray-700 rounded w-3/4" />
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 设置说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900">
        <h4 className="text-blue-900 dark:text-blue-400 mb-2">
          <Settings className="w-4 h-4 inline mr-2" />
          设置说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800 dark:text-blue-300">
          <li>• <strong>基本设置</strong>：配置平台名称、联系方式和系统公告</li>
          <li>• <strong>外观设置</strong>：设置系统默认主题（明亮/暗黑模式），保存后立即生效</li>
          <li>• 平台名称将显示在系统导航栏和登录页面</li>
          <li>• 系统公告会在登录页面显著位置展示</li>
          <li>• 所有设置修改后需要点击"保存设置"按钮才会生效</li>
        </ul>
      </Card>
    </div>
  );
}
