"use client";

import * as React from "react";
import { Save, Camera, RefreshCw, KeyRound } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  useUpdateProfileMutation,
  useUploadAvatarMutation,
  useRequestPasswordChangeMutation,
  useGetDealsQuery,
  useGetTeamsQuery,
} from "@/api/rtk";
import { useGetPipelinesQuery } from "@/api/rtk/pipelines-api";
import {
  ensureClientPublicIpForLogin,
  getStoredClientPublicIp,
} from "@/lib/client-public-ip";
import { UserAvatar } from "@/components/ui/user-avatar";
import { toast } from "sonner";
import { Card, CardHeader, FieldLabel } from "@/components/settings/ui";
import { AdminTwoFactorCard } from "@/components/settings/admin-two-factor-card";
import { isAdminUser } from "@/lib/permissions";
import { ProfileDealsTable } from "@/components/profile/profile-deals-table";
import { useAuthToken } from "@/hooks/use-auth-token";
import { buildStageNameMap } from "@/lib/notification-message";

interface Profile {
  id: string;
  name: string;
  email: string;
  avatar?: string | null;
  role?: { name: string } | null;
  profile?: { phone?: string | null; bio?: string | null } | null;
}

export function ProfileTab({ profile }: { profile: Profile }) {
  const { token: accessToken } = useAuthToken();
  const [name, setName] = React.useState(profile?.name ?? "");
  const [phone, setPhone] = React.useState(profile?.profile?.phone ?? "");
  const [bio, setBio] = React.useState(profile?.profile?.bio ?? "");

  const { data: allDealsSelection = [], isLoading: dealsLoading } = useGetDealsQuery(
    {},
    { skip: !accessToken }
  );
  const { data: teams = [] } = useGetTeamsQuery(undefined, {
    skip: !accessToken,
  });
  const { data: pipelines = [] } = useGetPipelinesQuery(undefined, {
    skip: !accessToken,
  });

  const profileDeals = React.useMemo(() => {
    if (!profile) return [];
    const isAdmin = profile.role?.name?.trim().toLowerCase() === "admin";
    const allDeals = (allDealsSelection ?? []) as any[];
    if (isAdmin) {
      return allDeals;
    }
    const pName = profile.name?.trim().toLowerCase();
    const ids = new Set([String(profile.id ?? "")].filter(Boolean));
    return allDeals.filter((deal) => {
      const ownerId = String(deal.ownerId ?? "");
      const ownerName = deal.createdBy?.trim().toLowerCase();
      return (ownerId && ids.has(ownerId)) || (!!pName && ownerName === pName);
    });
  }, [allDealsSelection, profile]);

  const isTeamLead = React.useMemo(() => {
    const userId = String(profile?.id ?? "");
    if (!userId) return false;
    return teams.some(
      (team) =>
        team.teamLead?.userId === userId ||
        (team.lead != null && String(team.lead) === userId),
    );
  }, [teams, profile?.id]);

  const stageNameMap = React.useMemo(
    () =>
      buildStageNameMap(
        pipelines.flatMap((pipeline) =>
          (pipeline.stages ?? []).map((stage) => ({
            id: stage.id,
            name: stage.name,
            subStages: (stage.subStages ?? []).map((subStage) => ({
              id: subStage.id,
              name: subStage.name,
            })),
          })),
        ),
      ),
    [pipelines],
  );
  const [updateProfile, { isLoading: saving }] = useUpdateProfileMutation();
  const [uploadAvatar, { isLoading: uploadingAvatar }] =
    useUploadAvatarMutation();
  const [requestPasswordReset, { isLoading: requestingPw }] =
    useRequestPasswordChangeMutation();
  const fileInputRef = React.useRef<HTMLInputElement>(null);

  React.useEffect(() => {
    if (profile?.name) setName(profile.name);
    if (profile?.profile?.phone) setPhone(profile.profile.phone ?? "");
    if (profile?.profile?.bio) setBio(profile.profile.bio ?? "");
  }, [profile?.name, profile?.profile?.phone, profile?.profile?.bio]);

  const handleSave = async () => {
    try {
      await updateProfile({ name, phone, bio }).unwrap();
      toast.success("Profile updated");
    } catch {
      toast.error("Failed to update profile");
    }
  };

  const handleRequestAdminPasswordReset = async () => {
    try {
      await ensureClientPublicIpForLogin();
      const clientPublicIp = getStoredClientPublicIp();
      const res = await requestPasswordReset({
        ...(clientPublicIp ? { clientPublicIp } : {}),
      }).unwrap();
      toast.success(res.message ?? "Request sent to administrators.");
    } catch {
      toast.error("Could not submit request. Try again later.");
    }
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !profile?.id) return;
    try {
      await uploadAvatar({ userId: profile.id, file }).unwrap();
      toast.success("Avatar updated successfully");
    } catch (error) {
      toast.error("Failed to upload avatar");
      console.error(error);
    }
  };

  return (
    <div className="space-y-5">
      <Card>
        <CardHeader
          title="Profile Information"
          description="Your public identity across the platform"
        />
        <div className="p-6 space-y-6">
          {/* Avatar row */}
          <div className="flex items-center gap-5">
            <div className="relative group">
              <input
                type="file"
                ref={fileInputRef}
                className="hidden"
                accept="image/*"
                onChange={handleFileChange}
              />
              <UserAvatar
                avatar={profile?.avatar}
                name={profile?.name}
                size="lg"
                className="rounded-2xl shadow-lg"
              />
              <button
                onClick={() => fileInputRef.current?.click()}
                disabled={uploadingAvatar}
                className="absolute inset-0 rounded-2xl bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
              >
                {uploadingAvatar ? (
                  <RefreshCw size={18} className="text-white animate-spin" />
                ) : (
                  <Camera size={18} className="text-white" />
                )}
              </button>
            </div>
            <div>
              <p className="text-[13px] font-semibold text-gray-900">
                {profile?.name || "—"}
              </p>
              <p className="text-[11px] text-gray-400 mt-0.5">
                {profile?.email || "—"}
              </p>
              {profile?.role?.name && (
                <span className="inline-flex items-center mt-2 text-[10px] font-bold px-2 py-0.5 rounded-full bg-[#6C63FF]/10 text-[#6C63FF]">
                  {profile.role.name}
                </span>
              )}
              {isTeamLead && (
                <span className="inline-flex items-center mt-2 ml-2 text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700">
                  Team Lead
                </span>
              )}
            </div>
          </div>

          {/* Fields */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <FieldLabel>Full Name</FieldLabel>
              <Input
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                placeholder="Your full name"
              />
            </div>
            <div>
              <FieldLabel>Email Address</FieldLabel>
              <Input
                value={profile?.email ?? ""}
                disabled
                className="h-10 text-[14px] bg-gray-100 border-gray-200 rounded-xl text-gray-400"
              />
            </div>
            <div>
              <FieldLabel>Phone Number</FieldLabel>
              <Input
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                placeholder="+1 (555) 000-0000"
              />
            </div>
            <div>
              <FieldLabel>Role</FieldLabel>
              <Input
                value={profile?.role?.name ?? "—"}
                disabled
                className="h-10 text-[14px] bg-gray-100 border-gray-200 rounded-xl text-gray-400"
              />
            </div>
            <div className="md:col-span-2">
              <FieldLabel>Bio</FieldLabel>
              <textarea
                value={bio}
                onChange={(e) => setBio(e.target.value)}
                rows={3}
                className="w-full text-[14px] bg-gray-50 border border-gray-200 rounded-xl px-3 py-2 resize-none focus:outline-none focus:ring-2 focus:ring-[#6C63FF]/30 focus:border-[#6C63FF]"
                placeholder="A short bio about yourself..."
              />
            </div>
          </div>
        </div>
        <div className="px-6 py-4 border-t border-gray-100/80 bg-gray-50/40 flex justify-end gap-2">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setName(profile?.name ?? "");
              setPhone(profile?.profile?.phone ?? "");
              setBio(profile?.profile?.bio ?? "");
            }}
          >
            Discard
          </Button>
          <Button
            variant="accentProfileSave"
            onClick={handleSave}
            disabled={saving}
          >
            {saving ? (
              <RefreshCw size={13} className="mr-1.5 animate-spin" />
            ) : (
              <Save size={13} className="mr-1.5" />
            )}
            Save Changes
          </Button>
        </div>
      </Card>

      {!isAdminUser(profile) && (
        <Card>
          <CardHeader
            title="Password"
            description="Self-service reset is disabled. Submit a request here while signed in, or use Forgot password on the sign-in page without signing in."
          />
          <div className="px-6 py-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">

            <Button
              type="button"
              variant="outlineMutedShrunk"
              onClick={() => void handleRequestAdminPasswordReset()}
              disabled={requestingPw}
            >
              {requestingPw ? (
                <RefreshCw size={14} className="mr-2 animate-spin" />
              ) : (
                <KeyRound size={14} className="mr-2" />
              )}
              Request admin password reset
            </Button>
          </div>
        </Card>
      )}

      {isAdminUser(profile) ? <AdminTwoFactorCard /> : null}

      {/* <div className="mt-8">
        <ProfileDealsTable
          deals={profileDeals}
          isLoading={dealsLoading}
          stageNameMap={stageNameMap}
        />
      </div> */}
    </div>
  );
}
