import { useEffect, useState } from "react";
import { Camera, Eye, EyeOff, Loader2, Trash2 } from "lucide-react";
import { toast } from "sonner";
import {
  changePassword,
  updateProfile,
  type AuthPlatform,
} from "@/lib/auth";
import { useAuthSession } from "@/hooks/useAuthSession";
import { ProfilePhotoDialog } from "@/components/auth/ProfilePhotoDialog";
import { UserAvatar } from "@/components/auth/UserAvatar";
import { PageHeader, SectionCard } from "@/components/ledger/Primitives";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

interface ProfilePageProps {
  platform: AuthPlatform;
}

export function ProfilePage({ platform }: ProfilePageProps) {
  const session = useAuthSession(platform);
  const isFirm = platform === "firm";

  const [name, setName] = useState(session?.name ?? "");
  const [company, setCompany] = useState(session?.company ?? "");
  const [profileLoading, setProfileLoading] = useState(false);

  useEffect(() => {
    if (session?.name != null) setName(session.name);
    if (session?.company != null) setCompany(session.company);
    else if (session) setCompany("");
  }, [session?.name, session?.company, session?.email]);

  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [passwordLoading, setPasswordLoading] = useState(false);
  const [photoOpen, setPhotoOpen] = useState(false);
  const [photoMode, setPhotoMode] = useState<"change" | "remove">("change");

  const displayName = session?.name || name || "User";

  const handleProfileSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setProfileLoading(true);
    const result = await updateProfile(platform, { name, company });
    if (!result.ok) {
      toast.error(result.error);
      setProfileLoading(false);
      return;
    }
    toast.success("Profile updated");
    setProfileLoading(false);
  };

  const handlePasswordSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (newPassword !== confirmPassword) {
      toast.error("New passwords do not match");
      return;
    }
    setPasswordLoading(true);
    const result = await changePassword(platform, { currentPassword, newPassword });
    if (!result.ok) {
      toast.error(result.error);
      setPasswordLoading(false);
      return;
    }
    toast.success("Password changed");
    setCurrentPassword("");
    setNewPassword("");
    setConfirmPassword("");
    setPasswordLoading(false);
  };

  return (
    <div className="mx-auto w-full max-w-[640px] space-y-5">
      <PageHeader
        title="My account"
        subtitle="Manage your profile and account settings."
        className="pb-1"
      />

      <SectionCard title="Profile" bodyClassName="px-5 py-5">
        <div className="flex items-center gap-4">
          <UserAvatar name={displayName} avatarUrl={session?.avatarUrl} size="xl" />
          <div className="min-w-0 flex-1">
            <p className="truncate text-[15px] font-semibold text-foreground">{displayName}</p>
            <p className="truncate text-[13px] text-muted-foreground">{session?.email}</p>
            <p className="mt-1.5 inline-flex rounded-full bg-primary-soft px-2 py-0.5 text-[10px] font-bold tracking-[0.14em] text-primary uppercase">
              {isFirm ? "Firm" : "Client"}
            </p>
            <div className="mt-3 flex flex-wrap gap-2">
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8 gap-1.5"
                onClick={() => {
                  setPhotoMode("change");
                  setPhotoOpen(true);
                }}
              >
                <Camera size={14} />
                Change photo
              </Button>
              {session?.avatarUrl ? (
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-8 gap-1.5 text-destructive hover:text-destructive"
                  onClick={() => {
                    setPhotoMode("remove");
                    setPhotoOpen(true);
                  }}
                >
                  <Trash2 size={14} />
                  Remove photo
                </Button>
              ) : null}
            </div>
          </div>
        </div>
      </SectionCard>

      <SectionCard title="Personal information" bodyClassName="px-5 py-5">
        <form onSubmit={handleProfileSave} className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="profile-name">Full name</Label>
            <Input
              id="profile-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Your name"
              required
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="profile-email">Email</Label>
            <Input id="profile-email" value={session?.email ?? ""} disabled />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="profile-company">Company name</Label>
            <Input
              id="profile-company"
              value={company}
              onChange={(e) => setCompany(e.target.value)}
              placeholder="Your company"
            />
          </div>
          <Button type="submit" disabled={profileLoading}>
            {profileLoading ? (
              <>
                <Loader2 className="animate-spin" size={16} aria-hidden="true" />
                Saving…
              </>
            ) : (
              "Save changes"
            )}
          </Button>
        </form>
      </SectionCard>

      <SectionCard title="Change password" bodyClassName="px-5 py-5">
        <form onSubmit={handlePasswordSave} className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="current-password">Current password</Label>
            <div className="relative">
              <Input
                id="current-password"
                type={showPassword ? "text" : "password"}
                autoComplete="current-password"
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
                className="pr-10"
                required
              />
              <button
                type="button"
                onClick={() => setShowPassword((v) => !v)}
                className="absolute top-1/2 right-2.5 -translate-y-1/2 rounded-md p-1 text-muted-foreground hover:text-foreground"
                aria-label={showPassword ? "Hide password" : "Show password"}
              >
                {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
              </button>
            </div>
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="new-password">New password</Label>
            <Input
              id="new-password"
              type={showPassword ? "text" : "password"}
              autoComplete="new-password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              minLength={8}
              required
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="confirm-password">Confirm new password</Label>
            <Input
              id="confirm-password"
              type={showPassword ? "text" : "password"}
              autoComplete="new-password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              minLength={8}
              required
            />
          </div>
          <Button type="submit" disabled={passwordLoading}>
            {passwordLoading ? (
              <>
                <Loader2 className="animate-spin" size={16} aria-hidden="true" />
                Updating…
              </>
            ) : (
              "Update password"
            )}
          </Button>
        </form>
      </SectionCard>

      <ProfilePhotoDialog
        platform={platform}
        open={photoOpen}
        onOpenChange={setPhotoOpen}
        name={displayName}
        avatarUrl={session?.avatarUrl}
        mode={photoMode}
      />
    </div>
  );
}
