'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { apiFetch } from '../../../lib/auth';
import { Skeleton } from '@/components/ui/skeleton';

interface Profile {
  nickname: string;
  email: string;
  phone: string;
  avatar: string;
}

export default function SettingsPage() {
  const router = useRouter();
  const [profile, setProfile] = useState<Profile>({ nickname: '', email: '', phone: '', avatar: '' });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [nickname, setNickname] = useState('');
  const [email, setEmail] = useState('');

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

  async function loadProfile() {
    try {
      const res = await apiFetch('/dashboard/profile');
      const data = await res.json();
      setProfile(data);
      setNickname(data.nickname || '');
      setEmail(data.email || '');
    } catch (e) { console.error(e) }
    setLoading(false);
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      await apiFetch('/dashboard/profile', {
        method: 'PUT',
        body: JSON.stringify({ nickname, email }),
      });
      alert('保存成功');
    } catch (e) { console.error(e) }
    setSaving(false);
  }

  async function handleLogout() {
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    router.push('/auth');
  }

  if (loading) return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Skeleton className="h-8 w-48 mb-6" />
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
        <Skeleton className="h-24 rounded-xl" />
        <Skeleton className="h-24 rounded-xl" />
        <Skeleton className="h-24 rounded-xl" />
      </div>
      <Skeleton className="h-64 w-full rounded-xl" />
    </div>
  );

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="mb-8">
        <button onClick={() => router.back()} className="text-sm text-muted-foreground hover:text-foreground mb-4 block">&larr; 返回</button>
        <h1 className="text-3xl font-bold text-foreground">设置</h1>
        <p className="mt-2 text-muted-foreground">管理你的账号偏好</p>
      </div>

      <form onSubmit={handleSave} className="bg-card rounded-2xl border border-border p-6 space-y-6">
        <h2 className="text-lg font-semibold text-foreground">个人信息</h2>
        
        <div>
          <label className="block text-sm font-medium text-foreground mb-1.5">昵称</label>
          <input
            type="text"
            value={nickname}
            onChange={e => setNickname(e.target.value)}
            className="w-full px-4 py-2.5 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-foreground mb-1.5">邮箱</label>
          <input
            type="email"
            value={email}
            onChange={e => setEmail(e.target.value)}
            className="w-full px-4 py-2.5 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
          />
        </div>

        <div className="flex gap-3">
          <button
            type="submit"
            disabled={saving}
            className="px-6 py-2.5 bg-brand-600 text-white rounded-xl text-sm font-medium hover:bg-brand-700 disabled:opacity-50"
          >
            {saving ? '保存中...' : '保存修改'}
          </button>
        </div>
      </form>

      <div className="bg-card rounded-2xl border border-border p-6 mt-6">
        <h2 className="text-lg font-semibold text-foreground mb-4">账号安全</h2>
        <button
          onClick={handleLogout}
          className="px-6 py-2.5 border border-red-200 text-red-600 rounded-xl text-sm font-medium hover:bg-red-50"
        >
          退出登录
        </button>
      </div>
    </div>
  );
}
