import { useGiteaConfigStore } from './store';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { giteaConfigSchema } from './store/schema';
import { toast } from 'sonner';
import { useLayoutStore } from '../../auth/store';
import { useShallow } from 'zustand/shallow';
import { useEffect } from 'react';


export const GiteaConfigPage = () => {
  const { config, setConfig, resetConfig, saveToRemote, loadFromRemote, checkConfig } = useGiteaConfigStore();
  const layoutStore = useLayoutStore(useShallow(state => ({ me: state.me })))

  useEffect(() => {
    if (layoutStore.me) {
      checkConfig({ isUser: !!layoutStore.me, reload: true })
    }
  }, [])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const result = giteaConfigSchema.safeParse(config);
    if (result.success) {
      toast.success('Gitea 配置已保存');
      setTimeout(() => {
        location.reload();
      }, 400);
    } else {
      console.error('验证错误:', result.error.format());
      toast.error('配置验证失败');
    }
  };

  const handleChange = (field: keyof typeof config, value: string) => {
    setConfig({ [field]: value });
  };

  return (
    <div className="container mx-auto max-w-2xl py-4 md:py-8 px-4">
      <div className="bg-white md:rounded-lg md:border md:shadow-sm">
        <div className="p-4 md:p-6 border-b">
          <h1 className="text-xl md:text-2xl font-bold">Gitea 配置</h1>
          <p className="text-sm text-muted-foreground mt-1">
            配置您的 Gitea API 设置。这些设置会保存在浏览器的本地存储中。
          </p>
        </div>
        <div className="p-4 md:p-6">
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="space-y-2">
              <Label htmlFor="gitea-url">Gitea 地址</Label>
              <Input
                id="gitea-url"
                type="url"
                value={config.GITEA_URL}
                onChange={(e) => handleChange('GITEA_URL', e.target.value)}
                placeholder="https://git.xiongxiao.me"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="gitea-token">Gitea Token</Label>
              <Input
                id="gitea-token"
                type="password"
                value={config.GITEA_TOKEN}
                onChange={(e) => handleChange('GITEA_TOKEN', e.target.value)}
                placeholder="请输入您的 Gitea Access Token"
              />
            </div>

            <div className="flex flex-col sm:flex-row gap-2 sm:gap-4">
              <Button type="submit" className="w-full sm:w-auto">保存配置</Button>
              <Button type="button" variant="outline" onClick={resetConfig} className="w-full sm:w-auto">
                重置为默认值
              </Button>
              {layoutStore.me && <>
                <Button type="button" variant="outline" onClick={loadFromRemote} className="w-full sm:w-auto">
                  获取远端配置
                </Button>
                <Button type="button" variant="outline" onClick={saveToRemote} className="w-full sm:w-auto">
                  保存到远端
                </Button>
              </>
              }
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default GiteaConfigPage;
