import { useEffect, useState } from 'react';
import { useNavigate, Link } from 'react-router';
import { Button, buttonVariants } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import PageLayout from '@/components/layout/PageLayout';
import { useAuthStore } from '@/stores/auth-store';
import { getUserStats, type UserStats } from '@/api/leaderboards';
import { updateProfile } from '@/api/users';
import { User, Flame, Trophy, BarChart3, LogOut, Pencil, Check, X } from 'lucide-react';

function formatTime(seconds: number) {
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${m}:${s.toString().padStart(2, '0')}`;
}

export default function Profile() {
  const user = useAuthStore((s) => s.user);
  const logout = useAuthStore((s) => s.logout);
  const loadUser = useAuthStore((s) => s.loadUser);
  const navigate = useNavigate();
  const [stats, setStats] = useState<UserStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [displayName, setDisplayName] = useState('');

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    getUserStats()
      .then(setStats)
      .catch(() => setStats(null))
      .finally(() => setLoading(false));
  }, [user, navigate]);

  const handleLogout = () => {
    logout();
    navigate('/');
  };

  const handleSaveProfile = async () => {
    try {
      await updateProfile({ displayName: displayName || undefined });
      await loadUser();
      setEditing(false);
    } catch {
      // Error handled by API client
    }
  };

  if (!user) return null;

  return (
    <PageLayout>
      <div className="space-y-6 py-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
              <User className="h-6 w-6 text-muted-foreground" />
            </div>
            <div>
              {editing ? (
                <div className="flex items-center gap-2">
                  <Input
                    value={displayName}
                    onChange={(e) => setDisplayName(e.target.value)}
                    placeholder="Display name"
                    className="h-8 w-40"
                  />
                  <Button variant="ghost" size="sm" onClick={handleSaveProfile}>
                    <Check className="h-4 w-4" />
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => setEditing(false)}>
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <h1 className="text-xl font-bold">{user.username}</h1>
                  <button
                    type="button"
                    onClick={() => {
                      setDisplayName('');
                      setEditing(true);
                    }}
                    className="text-muted-foreground hover:text-foreground"
                    aria-label="Edit display name"
                  >
                    <Pencil className="h-3.5 w-3.5" />
                  </button>
                </div>
              )}
              <p className="text-sm text-muted-foreground">{user.email}</p>
            </div>
          </div>
          <Button variant="ghost" size="sm" onClick={handleLogout}>
            <LogOut className="mr-1.5 h-4 w-4" />
            Sign Out
          </Button>
        </div>

        <Separator />

        {loading && (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-24 w-full" />
            ))}
          </div>
        )}

        {stats && (
          <>
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              <StatCard
                icon={<BarChart3 className="h-4 w-4" />}
                label="Games Played"
                value={stats.totalGamesPlayed.toString()}
              />
              <StatCard
                icon={<Trophy className="h-4 w-4" />}
                label="Best Score"
                value={stats.bestScore.toLocaleString()}
              />
              <StatCard
                icon={<Flame className="h-4 w-4" />}
                label="Current Streak"
                value={`${stats.currentStreak} day${stats.currentStreak !== 1 ? 's' : ''}`}
              />
              <StatCard
                icon={<Flame className="h-4 w-4" />}
                label="Longest Streak"
                value={`${stats.longestStreak} day${stats.longestStreak !== 1 ? 's' : ''}`}
              />
            </div>

            <div className="rounded-lg border border-border bg-card p-4">
              <div className="mb-1 flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Average Score</span>
                <span className="font-semibold">{stats.averageScore.toLocaleString()}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Total Score</span>
                <span className="font-semibold">{stats.totalScore.toLocaleString()}</span>
              </div>
            </div>

            <Link
              to="/achievements"
              className={buttonVariants({ variant: 'outline' })}
            >
              <Trophy className="mr-2 h-4 w-4" />
              View Achievements
            </Link>

            {stats.recentScores.length > 0 && (
              <div>
                <h2 className="mb-3 text-lg font-semibold">Recent Games</h2>
                <div className="rounded-lg border border-border">
                  <div className="grid grid-cols-[1fr_5rem_5rem_4rem] gap-2 border-b border-border bg-muted/50 px-4 py-2 text-xs font-medium uppercase text-muted-foreground">
                    <span>Date</span>
                    <span className="text-right">Score</span>
                    <span className="text-right">Time</span>
                    <span className="text-right">Chain</span>
                  </div>
                  {stats.recentScores.map((entry, i) => (
                    <div
                      key={i}
                      className="grid grid-cols-[1fr_5rem_5rem_4rem] gap-2 border-b border-border px-4 py-2.5 last:border-0"
                    >
                      <span className="text-sm">
                        {new Date(entry.date).toLocaleDateString()}
                      </span>
                      <span className="text-right font-medium tabular-nums">
                        {entry.score.toLocaleString()}
                      </span>
                      <span className="text-right text-sm text-muted-foreground">
                        {formatTime(entry.timeSeconds)}
                      </span>
                      <span className="text-right text-sm text-muted-foreground">
                        {entry.chainLength}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}

        {!loading && !stats && (
          <p className="py-8 text-center text-muted-foreground">
            No stats yet. Play a daily challenge to get started!
          </p>
        )}
      </div>
    </PageLayout>
  );
}

function StatCard({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
}) {
  return (
    <div className="rounded-lg border border-border bg-card p-4">
      <div className="mb-2 flex items-center gap-1.5 text-muted-foreground">
        {icon}
        <span className="text-xs font-medium">{label}</span>
      </div>
      <p className="text-2xl font-bold">{value}</p>
    </div>
  );
}
