"use client";

import { useEffect, useState } from "react";
import { useTheme } from "next-themes";
import { toast } from "sonner";
import type { AuthUserDto, UsageDto } from "@use2pdf/shared-types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { apiFetch, ApiRequestError } from "@/lib/api-client";
import { useAuth } from "@/lib/auth-context";
import { formatBytes } from "@/lib/format";

export default function SettingsPage() {
  const { user, logout } = useAuth();
  const { theme, setTheme } = useTheme();
  const [mounted, setMounted] = useState(false);

  const [name, setName] = useState("");
  const [savingName, setSavingName] = useState(false);

  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [changingPassword, setChangingPassword] = useState(false);

  const [usage, setUsage] = useState<UsageDto | null>(null);

  useEffect(() => {
    setMounted(true);
    apiFetch<{ user: AuthUserDto }>("/me")
      .then((res) => setName(res.user.name ?? ""))
      .catch(() => undefined);
    apiFetch<UsageDto>("/me/usage").then(setUsage).catch(() => undefined);
  }, []);

  async function saveProfile() {
    if (!name.trim()) {
      toast.error("Name cannot be empty");
      return;
    }
    setSavingName(true);
    try {
      await apiFetch("/me", { method: "PATCH", body: { name: name.trim() } });
      toast.success("Profile updated");
    } catch (err) {
      toast.error(err instanceof ApiRequestError ? err.message : "Could not save profile");
    } finally {
      setSavingName(false);
    }
  }

  async function changePassword() {
    if (newPassword !== confirmPassword) {
      toast.error("New passwords do not match");
      return;
    }
    if (newPassword.length < 8) {
      toast.error("New password must be at least 8 characters");
      return;
    }
    setChangingPassword(true);
    try {
      await apiFetch("/me/change-password", {
        method: "POST",
        body: { currentPassword, newPassword },
      });
      toast.success("Password changed. Please log in again.");
      await logout();
    } catch (err) {
      toast.error(err instanceof ApiRequestError ? err.message : "Could not change password");
    } finally {
      setChangingPassword(false);
    }
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100">Settings</h1>
        <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
          Manage your profile, security and preferences.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Profile</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Input label="Email" value={user?.email ?? ""} disabled />
          <Input
            label="Display name"
            placeholder="Your name"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
          <Button onClick={saveProfile} isLoading={savingName}>
            Save profile
          </Button>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Appearance</CardTitle>
        </CardHeader>
        <CardContent>
          {mounted && (
            <div className="flex gap-2">
              {(["light", "dark", "system"] as const).map((mode) => (
                <button
                  key={mode}
                  type="button"
                  onClick={() => setTheme(mode)}
                  className={`rounded-md border px-4 py-2 text-sm capitalize transition-colors ${
                    theme === mode
                      ? "border-brand-500 bg-brand-50 text-brand-700 dark:bg-brand-700/20 dark:text-brand-500"
                      : "border-slate-300 text-slate-600 dark:border-slate-600 dark:text-slate-300"
                  }`}
                >
                  {mode}
                </button>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Storage</CardTitle>
        </CardHeader>
        <CardContent>
          {usage ? (
            <p className="text-sm text-slate-600 dark:text-slate-300">
              {usage.fileCount} files using <strong>{formatBytes(usage.storageUsedBytes)}</strong> ·{" "}
              {usage.operationsTotal} operations run in total
            </p>
          ) : (
            <p className="text-sm text-slate-400">Loading…</p>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Change password</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Input
            label="Current password"
            type="password"
            autoComplete="current-password"
            value={currentPassword}
            onChange={(e) => setCurrentPassword(e.target.value)}
          />
          <Input
            label="New password"
            type="password"
            autoComplete="new-password"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
          />
          <Input
            label="Confirm new password"
            type="password"
            autoComplete="new-password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
          />
          <p className="text-xs text-slate-400">
            Changing your password signs you out of all sessions.
          </p>
          <Button onClick={changePassword} isLoading={changingPassword}>
            Change password
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
