"use client";

import { useState, useEffect, useRef } from "react";
import { useAppSelector } from "@/lib/store";
import { useRouter, useSearchParams } from "next/navigation";
import Image from "next/image";
import {
  useUpdateProfile,
  useChangePassword,
  useUploadAvatar,
  useRemoveAvatar,
} from "@/modules/auth/hooks/auth.hooks";
import { UpdateOrganization } from "@/modules/admin/organizations";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  User,
  Mail,
  Phone,
  Shield,
  KeyRound,
  Eye,
  EyeOff,
  Building2,
  Camera,
  Trash2,
} from "lucide-react";
import { capitalizeFirstLetter } from "@/lib/capitalize";

const roleLabelMap: Record<string, string> = {
  SUPERADMIN: "Super Admin",
  ADMIN: "Admin",
  MANAGER: "Manager",
  EMPLOYEE: "Staff",
  CLIENT: "Client",
  PARTNER: "Partner",
};

type Tab = "profile" | "security" | "organization";

export default function Profile() {
  const { user } = useAppSelector((state) => state.auth);
  const router = useRouter();
  const searchParams = useSearchParams();
  const tabParam = searchParams.get("tab") as Tab | null;
  const [activeTab, setActiveTab] = useState<Tab>(tabParam ?? "profile");
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (
      tabParam &&
      ["profile", "security", "organization"].includes(tabParam)
    ) {
      setActiveTab(tabParam as Tab);
    }
  }, [tabParam]);

  // --- Profile ---
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const { mutate: updateProfile, isPending: isUpdating } = useUpdateProfile();
  const { mutate: uploadAvatar, isPending: isUploading } = useUploadAvatar();
  const { mutate: removeAvatar, isPending: isRemoving } = useRemoveAvatar();

  useEffect(() => {
    if (user) {
      setName(user.name ?? "");
      setPhone(user.phone ?? "");
    }
  }, [user]);

  const handleProfileSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    updateProfile({
      name: capitalizeFirstLetter(name.trim()),
      phone: phone.trim() || undefined,
    });
  };

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) uploadAvatar(file);
    e.target.value = "";
  };

  // --- Password ---
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [pwError, setPwError] = useState("");
  const { mutate: changePassword, isPending: isChanging } = useChangePassword();

  const handlePasswordSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setPwError("");
    if (newPassword !== confirmPassword) {
      setPwError("New passwords do not match");
      return;
    }
    if (newPassword.length < 8) {
      setPwError("Password must be at least 8 characters");
      return;
    }
    if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/.test(newPassword)) {
      setPwError("Password must contain uppercase, lowercase, and a number");
      return;
    }
    changePassword(
      { currentPassword, newPassword },
      {
        onSuccess: () => {
          setCurrentPassword("");
          setNewPassword("");
          setConfirmPassword("");
          router.push("/profile?tab=profile");
        },
      }
    );
  };

  if (!user) return null;

  const initials = user.name
    .split(" ")
    .map((n) => n[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

  const tabs: { key: Tab; label: string; icon: React.ReactNode }[] = [
    {
      key: "profile",
      label: "Profile Information",
      icon: <User className="h-4 w-4" />,
    },
    {
      key: "security",
      label: "Security",
      icon: <KeyRound className="h-4 w-4" />,
    },
    ...(user.role === "ADMIN"
      ? [
          {
            key: "organization" as Tab,
            label: "Organization",
            icon: <Building2 className="h-4 w-4" />,
          },
        ]
      : []),
  ];

  return (
    <div className="space-y-6 w-full">
      <div>
        <h2 className="text-2xl font-bold tracking-tight text-foreground">
          My Profile
        </h2>
        <p className="text-muted-foreground text-sm mt-1">
          Manage your account information and security
        </p>
      </div>

      {/* Tab bar */}
      <div className="flex border-b border-border">
        {tabs.map((tab) => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            className={`flex items-center gap-2 px-5 py-3 text-sm font-medium border-b-2 transition-colors -mb-px ${
              activeTab === tab.key
                ? "border-primary text-primary"
                : "border-transparent text-muted-foreground hover:text-foreground hover:border-border"
            }`}
          >
            {tab.icon}
            {tab.label}
          </button>
        ))}
      </div>

      {/* Profile Tab */}
      {activeTab === "profile" && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
          {/* Left — Avatar Card */}
          <Card className="border-border bg-card shadow-sm lg:col-span-1">
            <CardContent className="p-6 flex flex-col items-center text-center gap-4">
              {/* Avatar */}
              <div className="relative group mt-2">
                <div className="h-24 w-24 rounded-full overflow-hidden border-4 border-primary/20 bg-primary/10 flex items-center justify-center shadow-md">
                  {user.avatarUrl ? (
                    <Image
                      src={user.avatarUrl}
                      alt={user.name}
                      width={96}
                      height={96}
                      className="object-cover w-full h-full"
                    />
                  ) : (
                    <span className="text-primary text-3xl font-bold">{initials}</span>
                  )}
                </div>
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  disabled={isUploading || isRemoving}
                  className="absolute inset-0 rounded-full bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer"
                >
                  <Camera className="h-5 w-5 text-white" />
                </button>
                <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={handleAvatarChange} />
              </div>

              {/* Name & role */}
              <div>
                <p className="font-bold text-foreground text-lg leading-tight">{user.name}</p>
                <p className="text-xs text-muted-foreground mt-0.5">{user.email}</p>
                <Badge variant="outline" className="mt-2 text-[11px] text-primary border-primary/30 bg-primary/5 px-2.5">
                  {roleLabelMap[user.role] ?? user.role}
                </Badge>
              </div>

              {/* Divider */}
              <div className="w-full border-t border-border" />

              {/* Meta info */}
              <div className="w-full space-y-2.5 text-left">
                <div className="flex items-center gap-2.5 text-xs">
                  <div className="h-7 w-7 rounded-md bg-primary/10 flex items-center justify-center flex-shrink-0">
                    <Mail className="h-3.5 w-3.5 text-primary" />
                  </div>
                  <div className="min-w-0">
                    <p className="text-[10px] text-muted-foreground uppercase tracking-wide">Email</p>
                    <p className="font-medium text-foreground truncate text-xs">{user.email}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2.5 text-xs">
                  <div className="h-7 w-7 rounded-md bg-primary/10 flex items-center justify-center flex-shrink-0">
                    <Phone className="h-3.5 w-3.5 text-primary" />
                  </div>
                  <div>
                    <p className="text-[10px] text-muted-foreground uppercase tracking-wide">Phone</p>
                    <p className="font-medium text-foreground text-xs">{user.phone || "—"}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2.5 text-xs">
                  <div className="h-7 w-7 rounded-md bg-primary/10 flex items-center justify-center flex-shrink-0">
                    <Shield className="h-3.5 w-3.5 text-primary" />
                  </div>
                  <div>
                    <p className="text-[10px] text-muted-foreground uppercase tracking-wide">Role</p>
                    <p className="font-medium text-foreground text-xs">{roleLabelMap[user.role] ?? user.role}</p>
                  </div>
                </div>
              </div>

              {/* Divider */}
              <div className="w-full border-t border-border" />

              {/* Avatar actions */}
              <div className="w-full flex flex-col gap-2">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  className="w-full h-8 text-xs gap-1.5"
                  disabled={isUploading || isRemoving}
                  onClick={() => fileInputRef.current?.click()}
                >
                  <Camera className="h-3.5 w-3.5" />
                  {isUploading ? "Uploading..." : user.avatarUrl ? "Replace Photo" : "Upload Photo"}
                </Button>
                {user.avatarUrl && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="w-full h-8 text-xs gap-1.5 text-destructive hover:text-destructive hover:bg-destructive/10"
                    disabled={isUploading || isRemoving}
                    onClick={() => removeAvatar()}
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                    {isRemoving ? "Removing..." : "Remove Photo"}
                  </Button>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Right — Edit Form */}
          <Card className="border-border bg-card shadow-sm lg:col-span-2">
            <CardHeader className="border-b border-border pb-4">
              <CardTitle className="text-base font-bold flex items-center gap-2">
                <User className="h-4 w-4 text-primary" /> Edit Profile
              </CardTitle>
              <p className="text-xs text-muted-foreground mt-0.5">Update your personal information</p>
            </CardHeader>
            <CardContent className="p-6">
              <form onSubmit={handleProfileSubmit} className="space-y-5">
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    Full Name <span className="text-destructive">*</span>
                  </Label>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      placeholder="Your full name"
                      required
                      className="pl-9 h-10 text-sm"
                    />
                  </div>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    Email Address
                  </Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      value={user.email}
                      disabled
                      className="pl-9 h-10 text-sm bg-muted/50 cursor-not-allowed"
                    />
                  </div>
                  <p className="text-[11px] text-muted-foreground">Email cannot be changed</p>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    Phone Number
                  </Label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      placeholder="10-15 digit number"
                      className="pl-9 h-10 text-sm"
                    />
                  </div>
                </div>

                <div className="flex justify-end pt-2">
                  <Button type="submit" size="sm" disabled={isUpdating} className="min-w-[130px] h-9">
                    {isUpdating ? "Saving..." : "Save Changes"}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Security Tab */}
      {activeTab === "security" && (
        <Card className="border-border bg-card shadow-sm w-full">
          <CardHeader className="border-b border-border">
            <CardTitle className="text-base font-bold flex items-center gap-2">
              <KeyRound className="h-4 w-4 text-primary" /> Change Password
            </CardTitle>
          </CardHeader>
          <CardContent className="p-6">
            <form onSubmit={handlePasswordSubmit} className="space-y-5">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    Current Password <span className="text-destructive">*</span>
                  </Label>
                  <div className="relative">
                    <Input
                      type={showCurrent ? "text" : "password"}
                      value={currentPassword}
                      onChange={(e) => setCurrentPassword(e.target.value)}
                      placeholder="Current password"
                      required
                      className="pr-10 h-9 text-sm"
                    />
                    <button
                      type="button"
                      onClick={() => setShowCurrent((v) => !v)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                      tabIndex={-1}
                    >
                      {showCurrent ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </button>
                  </div>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    New Password <span className="text-destructive">*</span>
                  </Label>
                  <div className="relative">
                    <Input
                      type={showNew ? "text" : "password"}
                      value={newPassword}
                      onChange={(e) => {
                        setNewPassword(e.target.value);
                        setPwError("");
                      }}
                      placeholder="Min 8 chars, A-Z, 0-9"
                      required
                      className="pr-10 h-9 text-sm"
                    />
                    <button
                      type="button"
                      onClick={() => setShowNew((v) => !v)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                      tabIndex={-1}
                    >
                      {showNew ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </button>
                  </div>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    Confirm Password <span className="text-destructive">*</span>
                  </Label>
                  <div className="relative">
                    <Input
                      type={showConfirm ? "text" : "password"}
                      value={confirmPassword}
                      onChange={(e) => {
                        setConfirmPassword(e.target.value);
                        setPwError("");
                      }}
                      placeholder="Repeat new password"
                      required
                      className="pr-10 h-9 text-sm"
                    />
                    <button
                      type="button"
                      onClick={() => setShowConfirm((v) => !v)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                      tabIndex={-1}
                    >
                      {showConfirm ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </button>
                  </div>
                </div>
              </div>

              {pwError && <p className="text-xs text-destructive">{pwError}</p>}

              <div className="flex justify-end pt-2">
                <Button
                  type="submit"
                  size="sm"
                  disabled={isChanging}
                  className="min-w-[140px]"
                >
                  {isChanging ? "Updating..." : "Update Password"}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      )}
      {/* Organization Tab */}
      {activeTab === "organization" && <UpdateOrganization />}
    </div>
  );
}
