'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useSelector } from 'react-redux'; // 1. Import useSelector from react-redux
import {
  KeyRound,
  ShieldAlert,
  CheckCircle2,
  Lock,
  User as UserIcon,
  Mail,
  Phone,
  Building,
  CreditCard,
  MapPin,
  Loader2,
  BadgeCheck,
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { profileSettingsSchema } from '@/schemas/auth.schema';
import { useChangePassword } from '@/services/users/mutations';
import { useSelfUser, useUser } from '@/services/users/queries';
import { RootState } from '@/store'; // 2. Adjust path to your RootState type definition

type ProfileSettingsValues = z.infer<typeof profileSettingsSchema>;

export default function UserProfileSettingsPage() {
  const [statusMessage, setStatusMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // 3. Retrieve user directly from Redux auth slice
  const authUser = useSelector((state: RootState) => state.auth.user);
  const userId = authUser?.id ?? null;

  // 4. Fetch comprehensive user data via TanStack Query
  const { data: userResponse, isLoading: isUserLoading, isError: isUserError } = useSelfUser(userId);
  // Extract the nested UserRecord directly
  const userData = userResponse;

  console.log("USER DATA:", userResponse);

  const changePasswordMutation = useChangePassword();

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ProfileSettingsValues>({
    resolver: zodResolver(profileSettingsSchema),
  });

  const onSubmit = (values: ProfileSettingsValues) => {
    if (!userId) {
      setStatusMessage({ type: 'error', text: 'User session invalid. Please log in again.' });
      return;
    }

    setStatusMessage(null);

    changePasswordMutation.mutate(
      {
        userId,
        payload: {
          currentPassword: values.currentPassword,
          newPassword: values.newPassword,
        },
      },
      {
        onSuccess: () => {
          setStatusMessage({ type: 'success', text: 'Password successfully updated.' });
          reset();
        },
        onError: (err: any) => {
          // Safe fallback for UniversalApiError
          const errorMessage = err?.message || 'Failed to update password.';
          setStatusMessage({ type: 'error', text: errorMessage });
        },
      }
    );
  };

  return (
    <div className="max-w-7xl mx-auto space-y-6 animate-in fade-in duration-300 pb-12">
      {/* HEADER SECTION */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-border/40 pb-4">
        <div>
          <h1 className="text-sm font-black tracking-widest text-foreground uppercase">
            ACCOUNT PROFILE & SECURITY
          </h1>
          <p className="text-[11px] font-medium text-muted-foreground/70">
            View your personal identity profile, organization details, and update security credentials.
          </p>
        </div>
      </div>

      {/* USER INFORMATION OVERVIEW CARD */}
      <Card className="shadow-none rounded-xl border border-border/40 bg-surface/90">
        <CardHeader className="border-b border-border/30 pb-4">
          <div className="flex items-center gap-2">
            <UserIcon className="h-4 w-4 text-muted-foreground" />
            <CardTitle className="text-xs font-bold uppercase tracking-wider text-foreground">
              Personal & Account Information
            </CardTitle>
          </div>
          <CardDescription className="text-[11px] text-muted-foreground">
            Overview of your account profile details and verified system credentials.
          </CardDescription>
        </CardHeader>

        <CardContent className="pt-6">
          {isUserLoading ? (
            <div className="flex items-center justify-center py-8 gap-2 text-xs text-muted-foreground font-medium">
              <Loader2 className="h-4 w-4 animate-spin text-primary" />
              <span>Fetching user profile details...</span>
            </div>
          ) : isUserError || !userData ? (
            <div className="p-3 rounded-lg border border-destructive/20 bg-destructive/5 text-destructive text-xs font-medium">
              Failed to load user information. Please try refreshing the page.
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 text-xs">
              {/* Full Name & Role */}
              <div className="p-3 rounded-lg bg-muted/20 border border-border/30 space-y-1">
                <span className="text-[10px] font-bold uppercase text-muted-foreground tracking-wider block">
                  Full Name & Role
                </span>
                <p className="font-bold text-foreground flex items-center gap-1.5">
                  {userData.firstName} {userData.lastName}
                  {userData.isEmailVerified && (
                    <BadgeCheck className="h-3.5 w-3.5 text-emerald-500 inline" />
                  )}
                </p>
                <p className="text-[10px] font-mono font-medium text-primary uppercase">
                  Role: {userData.role?.replace(/_/g, ' ')}
                </p>
              </div>

              {/* Email Address */}
              <div className="p-3 rounded-lg bg-muted/20 border border-border/30 space-y-1">
                <span className="text-[10px] font-bold uppercase text-muted-foreground tracking-wider block">
                  Email Address
                </span>
                <p className="font-medium text-foreground flex items-center gap-2">
                  <Mail className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                  <span>{userData.email}</span>
                </p>
              </div>

              {/* Phone Number */}
              <div className="p-3 rounded-lg bg-muted/20 border border-border/30 space-y-1">
                <span className="text-[10px] font-bold uppercase text-muted-foreground tracking-wider block">
                  Phone Number
                </span>
                <p className="font-medium text-foreground flex items-center gap-2">
                  <Phone className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                  <span>{userData.phone || 'Not provided'}</span>
                </p>
              </div>

              {/* Organization Info */}
              {userData.userProfile?.organizationName && (
                <div className="p-3 rounded-lg bg-muted/20 border border-border/30 space-y-1">
                  <span className="text-[10px] font-bold uppercase text-muted-foreground tracking-wider block">
                    Organization Name
                  </span>
                  <p className="font-medium text-foreground flex items-center gap-2">
                    <Building className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                    <span>{userData.userProfile.organizationName}</span>
                  </p>
                </div>
              )}

              {/* Address */}
              {userData.userProfile?.registeredOfficeAddress && (
                <div className="p-3 rounded-lg bg-muted/20 border border-border/30 space-y-1">
                  <span className="text-[10px] font-bold uppercase text-muted-foreground tracking-wider block">
                    Address
                  </span>
                  <p className="font-medium text-foreground flex items-start gap-2">
                    <MapPin className="h-3.5 w-3.5 text-muted-foreground shrink-0 mt-0.5" />
                    <span>
                      {userData.userProfile.registeredOfficeAddress}, {userData.userProfile.city},{' '}
                      {userData.userProfile.state} - {userData.userProfile.postalCode}
                    </span>
                  </p>
                </div>
              )}

              {/* Identity Identification */}
              {userData.userProfile?.panNumber && (
                <div className="p-3 rounded-lg bg-muted/20 border border-border/30 space-y-1">
                  <span className="text-[10px] font-bold uppercase text-muted-foreground tracking-wider block">
                    Tax / PAN Identifier
                  </span>
                  <p className="font-mono font-medium text-foreground flex items-center gap-2">
                    <CreditCard className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                    <span>{userData.userProfile.panNumber}</span>
                  </p>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* CHANGE PASSWORD SECURITY CARD */}
      <Card className="shadow-none rounded-xl border border-border/40 bg-surface/90">
        <CardHeader className="border-b border-border/30 pb-4">
          <div className="flex items-center gap-2">
            <KeyRound className="h-4 w-4 text-muted-foreground" />
            <CardTitle className="text-xs font-bold uppercase tracking-wider text-foreground">
              Change Password
            </CardTitle>
          </div>
          <CardDescription className="text-[11px] text-muted-foreground">
            Ensure your account uses a strong, unique password to prevent unauthorized access.
          </CardDescription>
        </CardHeader>

        <CardContent className="pt-6">
          {/* STATUS NOTIFICATION BANNER */}
          {statusMessage && (
            <div
              className={`mb-6 p-3 rounded-lg border text-xs font-semibold flex items-center gap-2 ${
                statusMessage.type === 'success'
                  ? 'border-emerald-500/20 bg-emerald-500/10 text-emerald-600'
                  : 'border-destructive/20 bg-destructive/5 text-destructive'
              }`}
            >
              {statusMessage.type === 'success' ? (
                <CheckCircle2 className="h-4 w-4 shrink-0" />
              ) : (
                <ShieldAlert className="h-4 w-4 shrink-0" />
              )}
              <span>{statusMessage.text}</span>
            </div>
          )}

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 max-w-xl">
            {/* CURRENT PASSWORD */}
            <div className="space-y-1.5">
              <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                Current Password
              </label>
              <Input
                type="password"
                placeholder="••••••••••••"
                className="h-9 text-xs bg-background border-border/60 focus-visible:ring-1"
                {...register('currentPassword')}
              />
              {errors.currentPassword && (
                <p className="text-[11px] font-medium text-destructive">{errors.currentPassword.message}</p>
              )}
            </div>

            {/* NEW PASSWORD */}
            <div className="space-y-1.5">
              <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                New Password
              </label>
              <Input
                type="password"
                placeholder="••••••••••••"
                className="h-9 text-xs bg-background border-border/60 focus-visible:ring-1"
                {...register('newPassword')}
              />
              {errors.newPassword && (
                <p className="text-[11px] font-medium text-destructive">{errors.newPassword.message}</p>
              )}
            </div>

            {/* CONFIRM PASSWORD */}
            <div className="space-y-1.5">
              <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                Confirm New Password
              </label>
              <Input
                type="password"
                placeholder="••••••••••••"
                className="h-9 text-xs bg-background border-border/60 focus-visible:ring-1"
                {...register('confirmPassword')}
              />
              {errors.confirmPassword && (
                <p className="text-[11px] font-medium text-destructive">{errors.confirmPassword.message}</p>
              )}
            </div>

            {/* ACTION FOOTER */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pt-4 border-t border-border/30 mt-6">
              <Button
                type="submit"
                disabled={changePasswordMutation.isPending}
                className="h-8 rounded-md px-4 text-[11px] font-bold tracking-wider uppercase gap-1.5 bg-foreground text-background hover:bg-foreground/90 cursor-pointer"
              >
                <Lock className="h-3 w-3" />
                <span>{changePasswordMutation.isPending ? 'Updating Key...' : 'Update Password'}</span>
              </Button>

              <Link
                href="/forgot-password"
                className="text-[11px] font-semibold text-muted-foreground hover:text-foreground underline-offset-4 hover:underline transition-colors"
              >
                Forgot your password?
              </Link>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}