﻿"use client";

import { Badge } from "@/components/ui/badge";

import type React from "react";

import { Suspense, useEffect, useState, useRef } from "react";
import { HotelPageWrapper } from "@/roles/hotel/components/hotel-page-wrapper";
import { ProfileLoadingSkeleton } from "@/roles/hotel/components/profile/profile-loading-skeleton";
import { useSearchParams } from "next/navigation";
import { cn, getStorageUrl } from "@/lib/utils";
import {
  getProfileAction,
  updateProfileAction,
} from "@/features/users/actions/profile-actions";
import type { User as ProfileUser } from "@/core/api/services/auth/auth.types";
import {
  User,
  Shield,
  Bell,
  Camera,
  Save,
  Eye,
  EyeOff,
  Loader2,
} from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { Cropper, type CropperRef } from "react-advanced-cropper";

const profileTabs = [
  { name: "Profile", param: "profile", icon: User },
  { name: "Security", param: "security", icon: Shield },
  { name: "Notifications", param: "notifications", icon: Bell },
];

const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/jpg", "image/png"]);
const ALLOWED_IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png"]);
const HOTEL_PROFILE_IMAGE_UPDATED_EVENT = "hotel-profile-image-updated";

function isAllowedProfileImage(file: File) {
  const extension = file.name.split(".").pop()?.toLowerCase();

  return (
    ALLOWED_IMAGE_TYPES.has(file.type.toLowerCase()) ||
    (!!extension && ALLOWED_IMAGE_EXTENSIONS.has(extension))
  );
}

interface ManageProfileClientPageProps {
  initialTab: string;
}

const initialHotelData = {
  firstName: "",
  lastName: "",
  email: "",
  phone: "",
  address: "",
  officeAddress: "",
  gstNumber: "",
  panNumber: "",
  licenseNumber: "",
  status: "",
  reasonForReject: "",
  reasonForBlock: "",
  gstCertificate: "",
  panDocument: "",
  licenseDocument: "",
  msmeCertificate: "",
  businessDocument: "",
  profileImage: "/placeholder.png?height=200&width=200",
};

function normalizeText(value: string | null | undefined) {
  return value ?? "";
}

function getProfileImageSrc(value: string | null | undefined, cacheKey?: number) {
  if (!value?.trim()) {
    return initialHotelData.profileImage;
  }

  if (value.startsWith("data:") || value.startsWith("blob:")) {
    return value;
  }

  const imageUrl = getStorageUrl(value);

  if (!cacheKey) {
    return imageUrl;
  }

  const separator = imageUrl.includes("?") ? "&" : "?";
  return `${imageUrl}${separator}v=${cacheKey}`;
}

function mapProfileToHotelData(profile: ProfileUser) {
  return {
    firstName: normalizeText(profile.first_name),
    lastName: normalizeText(profile.last_name),
    email: normalizeText(profile.email),
    phone: normalizeText(profile.phone_number),
    address: normalizeText(profile.address),
    officeAddress: normalizeText(profile.office_address),
    gstNumber: normalizeText(profile.gst_number),
    panNumber: normalizeText(profile.pan_number),
    licenseNumber: normalizeText(profile.license_number),
    status: normalizeText(profile.status),
    reasonForReject: normalizeText(profile.reason_for_reject),
    reasonForBlock: normalizeText(profile.reason_for_block),
    gstCertificate: normalizeText(profile.gst_certificate),
    panDocument: normalizeText(profile.pan_document),
    licenseDocument: normalizeText(profile.license_document),
    msmeCertificate: normalizeText(profile.msme_certificate),
    businessDocument: normalizeText(profile.business_document),
    profileImage: getProfileImageSrc(profile.profile_image),
  };
}

function getDocumentName(url: string) {
  try {
    return decodeURIComponent(new URL(url).pathname.split("/").pop() || url);
  } catch {
    return url.split("/").pop() || url;
  }
}

function DocumentLink({ label, url }: { label: string; url: string }) {
  if (!url) {
    return null;
  }

  return (
    <a
      href={url}
      target="_blank"
      rel="noreferrer"
      className="text-sm text-primary underline-offset-4 hover:underline"
    >
      {label}: {getDocumentName(url)}
    </a>
  );
}

export function ManageProfileClientPage({
  initialTab,
}: ManageProfileClientPageProps) {
  const searchParams = useSearchParams();
  const tab = searchParams.get("tab") || initialTab;
  const toast = useToastEnhanced();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const cropperRef = useRef<CropperRef>(null);

  // Profile state
  const [hotelData, setHotelData] = useState(initialHotelData);
  const [isProfileLoading, setIsProfileLoading] = useState(true);
  const [profileError, setProfileError] = useState<string | null>(null);
  const [isProfileSaving, setIsProfileSaving] = useState(false);
  const [isImageUploading, setIsImageUploading] = useState(false);
  const [profileImage, setProfileImage] = useState(
    initialHotelData.profileImage
  );
  const [cropperOpen, setCropperOpen] = useState(false);
  const [cropSource, setCropSource] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;

    const fetchProfile = async () => {
      setIsProfileLoading(true);
      setProfileError(null);

      try {
        const result = await getProfileAction();

        if (!isMounted) {
          return;
        }

        if (result.success && result.data) {
          const nextHotelData = mapProfileToHotelData(result.data);
          setHotelData(nextHotelData);
          setProfileImage(nextHotelData.profileImage);
        } else {
          setProfileError(result.error || "Failed to load profile.");
        }
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setProfileError(
          error instanceof Error ? error.message : "Failed to load profile."
        );
      } finally {
        if (isMounted) {
          setIsProfileLoading(false);
        }
      }
    };

    fetchProfile();

    return () => {
      isMounted = false;
    };
  }, []);

  // Security state
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isPasswordSaving, setIsPasswordSaving] = useState(false);

  // Notification state
  const [notifications, setNotifications] = useState({
    emailBookings: true,
    emailPayments: true,
    emailMarketing: false,
    smsBookings: true,
    smsPayments: true,
    pushNotifications: true,
  });

  const handleImageClick = () => {
    fileInputRef.current?.click();
  };

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

    if (!file) {
      return;
    }

    if (!isAllowedProfileImage(file)) {
      toast.error({
        title: "Invalid file type",
        description: "Please select a JPG, JPEG, or PNG image.",
      });
      return;
    }

    const maxSizeInBytes = 5 * 1024 * 1024;
    if (file.size > maxSizeInBytes) {
      toast.error({
        title: "File too large",
        description: "Please select an image under 5MB.",
      });
      return;
    }

    if (cropSource) {
      URL.revokeObjectURL(cropSource);
    }

    setCropSource(URL.createObjectURL(file));
    setCropperOpen(true);
  };

  const handleCropperOpenChange = (open: boolean) => {
    setCropperOpen(open);

    if (!open && !isImageUploading && cropSource) {
      URL.revokeObjectURL(cropSource);
      setCropSource(null);
    }
  };

  const uploadProfileImage = async (profileImageFile: File) => {
    const formData = new FormData();
    formData.append("profile_image", profileImageFile);

    const response = await fetch("/api/profile/change-image", {
      method: "POST",
      body: formData,
    });

    const result = (await response.json().catch(() => null)) as {
      success?: boolean;
      message?: string;
      data?: unknown;
    } | null;

    if (!response.ok || result?.success === false) {
      throw new Error(result?.message || "Failed to update profile photo.");
    }

    return result?.data;
  };

  const refreshProfileImage = async () => {
    const result = await getProfileAction();

    if (result.success && result.data) {
      const nextHotelData = mapProfileToHotelData(result.data);
      const nextProfileImage = getProfileImageSrc(
        result.data.profile_image,
        Date.now()
      );

      setHotelData(nextHotelData);
      setProfileImage(nextProfileImage);
      return nextProfileImage;
    }

    return null;
  };

  const handleCropAndUpload = async () => {
    const canvas = cropperRef.current?.getCanvas();

    if (!canvas) {
      toast.error({
        title: "Crop failed",
        description: "Unable to crop image. Please try another image.",
      });
      return;
    }

    setIsImageUploading(true);

    try {
      const blob = await new Promise<Blob | null>((resolve) =>
        canvas.toBlob(resolve, "image/png")
      );

      if (!blob) {
        throw new Error("Unable to generate cropped image.");
      }

      const croppedFile = new File([blob], `profile-${Date.now()}.png`, {
        type: "image/png",
      });

      const uploadedImage = await uploadProfileImage(croppedFile);
      const previewUrl = URL.createObjectURL(blob);
      const uploadedImageUrl =
        typeof uploadedImage === "string" && uploadedImage.trim()
          ? getProfileImageSrc(uploadedImage, Date.now())
          : null;

      if (uploadedImageUrl) {
        setProfileImage(uploadedImageUrl);
        URL.revokeObjectURL(previewUrl);
        window.dispatchEvent(
          new CustomEvent(HOTEL_PROFILE_IMAGE_UPDATED_EVENT, {
            detail: { profileImage: uploadedImageUrl },
          })
        );
      } else {
        setProfileImage(previewUrl);
        const refreshedProfileImage = await refreshProfileImage();

        if (refreshedProfileImage) {
          URL.revokeObjectURL(previewUrl);
          window.dispatchEvent(
            new CustomEvent(HOTEL_PROFILE_IMAGE_UPDATED_EVENT, {
              detail: { profileImage: refreshedProfileImage },
            })
          );
        }
      }
      setCropperOpen(false);
      if (cropSource) {
        URL.revokeObjectURL(cropSource);
        setCropSource(null);
      }

      toast.success({
        title: "Photo Updated",
        description: "Your profile photo has been updated successfully.",
      });
    } catch (error) {
      toast.error({
        title: "Upload failed",
        description:
          error instanceof Error
            ? error.message
            : "Failed to update profile photo.",
      });
    } finally {
      setIsImageUploading(false);
    }
  };

  const handleProfileSave = async () => {
    setIsProfileSaving(true);

    try {
      const result = await updateProfileAction({
        first_name: hotelData.firstName,
        last_name: hotelData.lastName,
        phone_number: hotelData.phone,
        address: hotelData.address || null,
        office_address: hotelData.officeAddress || null,
      });

      if (!result.success) {
        throw new Error(result.error || "Failed to update profile.");
      }

      toast.success({
        title: "Profile Updated",
        description: "Your profile information has been saved successfully.",
      });
    } catch (error) {
      toast.error({
        title: "Update failed",
        description:
          error instanceof Error
            ? error.message
            : "Failed to update profile information.",
      });
    } finally {
      setIsProfileSaving(false);
    }
  };

  const handlePasswordChange = async () => {
    if (!currentPassword || !newPassword || !confirmPassword) {
      toast.error({
        title: "Missing Fields",
        description: "Please fill in all password fields.",
      });
      return;
    }

    if (newPassword !== confirmPassword) {
      toast.error({
        title: "Password Mismatch",
        description: "New password and confirm password do not match.",
      });
      return;
    }

    if (newPassword.length < 8) {
      toast.error({
        title: "Weak Password",
        description: "Password must be at least 8 characters long.",
      });
      return;
    }

    setIsPasswordSaving(true);
    // Simulate API call
    await new Promise((resolve) => setTimeout(resolve, 1000));
    setIsPasswordSaving(false);
    setCurrentPassword("");
    setNewPassword("");
    setConfirmPassword("");
    toast.success({
      title: "Password Changed",
      description: "Your password has been updated successfully.",
    });
  };

  const handleNotificationSave = async () => {
    toast.success({
      title: "Preferences Saved",
      description: "Your notification preferences have been updated.",
    });
  };

  return (
    <HotelPageWrapper>
      <Suspense fallback={<ProfileLoadingSkeleton />}>
        <div className="space-y-6">
          {/* Page Header */}
          <div>
            <h1 className="text-3xl font-bold tracking-tight text-foreground">
              Manage Profile
            </h1>
            <p className="text-muted-foreground mt-1">
              Update your profile information and account settings
            </p>
          </div>

          {/* Profile Tabs */}
          <div className="flex flex-col lg:flex-row gap-6">
            {/* Sidebar */}
            <aside className="w-full lg:w-60 shrink-0">
              <div className="sticky top-24">
                <div className="bg-card border rounded-xl p-3 shadow-sm">
                  <nav
                    className="flex flex-col gap-1"
                    aria-label="Profile navigation"
                  >
                    {profileTabs.map((item) => {
                      const Icon = item.icon;
                      const active = tab === item.param;

                      return (
                        <Link
                          key={item.param}
                          href={`/hotel/manage-profile?tab=${item.param}`}
                          className={cn(
                            "flex items-center gap-3 px-3 py-2.5 rounded-lg font-medium text-sm transition-all duration-200",
                            active
                              ? "bg-slate-900 dark:bg-white text-white dark:text-slate-900 shadow-md"
                              : "text-muted-foreground hover:text-foreground hover:bg-muted"
                          )}
                        >
                          <Icon className="h-4 w-4" />
                          <span>{item.name}</span>
                        </Link>
                      );
                    })}
                  </nav>
                </div>
              </div>
            </aside>

            {/* Content */}
            <div className="flex-1 max-w-3xl">
              {/* Profile Tab */}
              {tab === "profile" && (
                <div className="space-y-6">
                  {isProfileLoading && <ProfileLoadingSkeleton />}

                  {!isProfileLoading && profileError && (
                    <Card className="border-destructive/40">
                      <CardContent className="pt-6">
                        <p className="text-sm text-destructive">
                          {profileError}
                        </p>
                      </CardContent>
                    </Card>
                  )}

                  {!isProfileLoading && !profileError && (
                    <>
                      {/* Profile Photo Card */}
                      <Card>
                        <CardHeader>
                          <CardTitle>Profile Photo</CardTitle>
                          <CardDescription>
                            Update your hotel profile photo
                          </CardDescription>
                        </CardHeader>
                        <CardContent>
                          <div className="flex items-center gap-6">
                            <div className="relative group">
                              <div className="h-24 w-24 rounded-full overflow-hidden border-4 border-muted">
                                <Image
                                  src={profileImage || "/placeholder.png"}
                                  alt="Profile"
                                  width={96}
                                  height={96}
                                  className="h-full w-full object-cover"
                                />
                              </div>
                              <button
                                type="button"
                                onClick={handleImageClick}
                                disabled={isImageUploading}
                                className="absolute inset-0 flex items-center justify-center bg-black/50 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                                aria-label="Change profile photo"
                              >
                                {isImageUploading ? (
                                  <Loader2 className="h-6 w-6 animate-spin text-white" />
                                ) : (
                                  <Camera className="h-6 w-6 text-white" />
                                )}
                              </button>
                              <input
                                ref={fileInputRef}
                                type="file"
                                accept="image/*"
                                onChange={handleImageChange}
                                className="hidden"
                              />
                            </div>
                            <div>
                              <Button
                                variant="outline"
                                onClick={handleImageClick}
                                disabled={isImageUploading}
                              >
                                {isImageUploading ? (
                                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                ) : (
                                  <Camera className="h-4 w-4 mr-2" />
                                )}
                                {isImageUploading
                                  ? "Uploading..."
                                  : "Change Photo"}
                              </Button>
                              <p className="text-xs text-muted-foreground mt-2">
                                JPG, JPEG or PNG. Max size 5MB.
                              </p>
                            </div>
                          </div>
                        </CardContent>
                      </Card>

                      <Dialog
                        open={cropperOpen}
                        onOpenChange={handleCropperOpenChange}
                      >
                        <DialogContent className="sm:max-w-2xl">
                          <DialogHeader>
                            <DialogTitle>Crop Profile Photo</DialogTitle>
                            <DialogDescription>
                              Adjust your image before updating your hotel
                              profile photo.
                            </DialogDescription>
                          </DialogHeader>

                          {cropSource && (
                            <div className="h-[420px] w-full overflow-hidden rounded-md border">
                              <Cropper
                                ref={cropperRef}
                                src={cropSource}
                                className="h-full w-full"
                                stencilProps={{
                                  aspectRatio: 1,
                                }}
                              />
                            </div>
                          )}

                          <DialogFooter>
                            <Button
                              type="button"
                              variant="outline"
                              onClick={() => handleCropperOpenChange(false)}
                              disabled={isImageUploading}
                            >
                              Cancel
                            </Button>
                            <Button
                              type="button"
                              onClick={handleCropAndUpload}
                              disabled={isImageUploading}
                            >
                              {isImageUploading && (
                                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                              )}
                              {isImageUploading
                                ? "Uploading..."
                                : "Crop & Upload"}
                            </Button>
                          </DialogFooter>
                        </DialogContent>
                      </Dialog>

                      {/* Basic Information Card */}
                      <Card>
                        <CardHeader>
                          <CardTitle>Basic Information</CardTitle>
                          <CardDescription>
                            Update your profile and contact details
                          </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                          <div className="grid gap-4 sm:grid-cols-2">
                            <div className="space-y-2">
                              <Label htmlFor="firstName">First Name</Label>
                              <Input
                                id="firstName"
                                value={hotelData.firstName}
                                onChange={(e) =>
                                  setHotelData({
                                    ...hotelData,
                                    firstName: e.target.value,
                                  })
                                }
                              />
                            </div>
                            <div className="space-y-2">
                              <Label htmlFor="lastName">Last Name</Label>
                              <Input
                                id="lastName"
                                value={hotelData.lastName}
                                onChange={(e) =>
                                  setHotelData({
                                    ...hotelData,
                                    lastName: e.target.value,
                                  })
                                }
                              />
                            </div>
                          </div>
                          <div className="grid gap-4 sm:grid-cols-2">
                            <div className="space-y-2">
                              <Label htmlFor="email">Email Address</Label>
                              <Input
                                id="email"
                                type="email"
                                value={hotelData.email}
                                readOnly
                                className="bg-muted/50"
                              />
                            </div>
                            <div className="space-y-2">
                              <Label htmlFor="phone">Phone Number</Label>
                              <Input
                                id="phone"
                                value={hotelData.phone}
                                onChange={(e) =>
                                  setHotelData({
                                    ...hotelData,
                                    phone: e.target.value,
                                  })
                                }
                              />
                            </div>
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="officeAddress">
                              Office Address
                            </Label>
                            <Textarea
                              id="officeAddress"
                              rows={4}
                              value={hotelData.officeAddress}
                              onChange={(e) =>
                                setHotelData({
                                  ...hotelData,
                                  officeAddress: e.target.value,
                                })
                              }
                            />
                          </div>
                        </CardContent>
                      </Card>

                      {/* Address Card */}
                      <Card>
                        <CardHeader>
                          <CardTitle>Address Details</CardTitle>
                          <CardDescription>
                            Update your hotel location
                          </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                          <div className="space-y-2">
                            <Label htmlFor="address">Address</Label>
                            <Textarea
                              id="address"
                              rows={4}
                              value={hotelData.address}
                              onChange={(e) =>
                                setHotelData({
                                  ...hotelData,
                                  address: e.target.value,
                                })
                              }
                            />
                          </div>
                        </CardContent>
                      </Card>

                      {/* Business Details Card */}
                      <Card>
                        <CardHeader>
                          <CardTitle>Business Details</CardTitle>
                          <CardDescription>
                            Your tax and business registration information
                          </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                          <div className="grid gap-4 sm:grid-cols-2">
                            <div className="space-y-2">
                              <Label htmlFor="gstNumber">GST Number</Label>
                              <Input
                                id="gstNumber"
                                value={hotelData.gstNumber}
                                readOnly
                                className="bg-muted/50"
                              />
                            </div>
                            <div className="space-y-2">
                              <Label htmlFor="panNumber">PAN Number</Label>
                              <Input
                                id="panNumber"
                                value={hotelData.panNumber}
                                readOnly
                                className="bg-muted/50"
                              />
                            </div>
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="licenseNumber">
                              License Number
                            </Label>
                            <Input
                              id="licenseNumber"
                              value={hotelData.licenseNumber}
                              readOnly
                              className="bg-muted/50"
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <DocumentLink
                              label="GST Certificate"
                              url={hotelData.gstCertificate}
                            />
                            <DocumentLink
                              label="PAN Document"
                              url={hotelData.panDocument}
                            />
                            <DocumentLink
                              label="License Document"
                              url={hotelData.licenseDocument}
                            />
                            <DocumentLink
                              label="MSME Certificate"
                              url={hotelData.msmeCertificate}
                            />
                            <DocumentLink
                              label="Business Document"
                              url={hotelData.businessDocument}
                            />
                          </div>
                        </CardContent>
                      </Card>

                      <Card>
                        <CardHeader>
                          <CardTitle>Account Status</CardTitle>
                          <CardDescription>
                            Current verification status from your profile
                          </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-3">
                          <Badge variant="secondary">
                            {hotelData.status || "Unknown"}
                          </Badge>
                          {hotelData.reasonForReject && (
                            <p className="text-sm text-muted-foreground">
                              Rejection reason: {hotelData.reasonForReject}
                            </p>
                          )}
                          {hotelData.reasonForBlock && (
                            <p className="text-sm text-muted-foreground">
                              Block reason: {hotelData.reasonForBlock}
                            </p>
                          )}
                        </CardContent>
                      </Card>

                      {/* Save Button */}
                      <div className="flex justify-end">
                        <Button
                          onClick={handleProfileSave}
                          disabled={isProfileSaving}
                        >
                          {isProfileSaving ? (
                            <>
                              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                              Saving...
                            </>
                          ) : (
                            <>
                              <Save className="h-4 w-4 mr-2" />
                              Save Changes
                            </>
                          )}
                        </Button>
                      </div>
                    </>
                  )}
                </div>
              )}

              {/* Security Tab */}
              {tab === "security" && (
                <div className="space-y-6">
                  <Card>
                    <CardHeader>
                      <CardTitle>Change Password</CardTitle>
                      <CardDescription>
                        Update your account password for security
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="space-y-2">
                        <Label htmlFor="currentPassword">
                          Current Password
                        </Label>
                        <div className="relative">
                          <Input
                            id="currentPassword"
                            type={showCurrentPassword ? "text" : "password"}
                            value={currentPassword}
                            onChange={(e) => setCurrentPassword(e.target.value)}
                            placeholder="Enter current password"
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                            onClick={() =>
                              setShowCurrentPassword(!showCurrentPassword)
                            }
                          >
                            {showCurrentPassword ? (
                              <EyeOff className="h-4 w-4 text-muted-foreground" />
                            ) : (
                              <Eye className="h-4 w-4 text-muted-foreground" />
                            )}
                          </Button>
                        </div>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="newPassword">New Password</Label>
                        <div className="relative">
                          <Input
                            id="newPassword"
                            type={showNewPassword ? "text" : "password"}
                            value={newPassword}
                            onChange={(e) => setNewPassword(e.target.value)}
                            placeholder="Enter new password"
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                            onClick={() => setShowNewPassword(!showNewPassword)}
                          >
                            {showNewPassword ? (
                              <EyeOff className="h-4 w-4 text-muted-foreground" />
                            ) : (
                              <Eye className="h-4 w-4 text-muted-foreground" />
                            )}
                          </Button>
                        </div>
                        <p className="text-xs text-muted-foreground">
                          Password must be at least 8 characters long
                        </p>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="confirmPassword">
                          Confirm New Password
                        </Label>
                        <div className="relative">
                          <Input
                            id="confirmPassword"
                            type={showConfirmPassword ? "text" : "password"}
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                            placeholder="Confirm new password"
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                            onClick={() =>
                              setShowConfirmPassword(!showConfirmPassword)
                            }
                          >
                            {showConfirmPassword ? (
                              <EyeOff className="h-4 w-4 text-muted-foreground" />
                            ) : (
                              <Eye className="h-4 w-4 text-muted-foreground" />
                            )}
                          </Button>
                        </div>
                      </div>
                      <div className="flex justify-end pt-4">
                        <Button
                          onClick={handlePasswordChange}
                          disabled={isPasswordSaving}
                        >
                          {isPasswordSaving ? (
                            <>
                              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                              Updating...
                            </>
                          ) : (
                            <>
                              <Shield className="h-4 w-4 mr-2" />
                              Update Password
                            </>
                          )}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>Two-Factor Authentication</CardTitle>
                      <CardDescription>
                        Add an extra layer of security to your account
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Enable 2FA</p>
                          <p className="text-sm text-muted-foreground">
                            Secure your account with two-factor authentication
                          </p>
                        </div>
                        <Switch />
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>Login Sessions</CardTitle>
                      <CardDescription>
                        Manage your active login sessions
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-4">
                        <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                          <div>
                            <p className="font-medium text-sm">
                              Current Session
                            </p>
                            <p className="text-xs text-muted-foreground">
                              Chrome on Windows - Active now
                            </p>
                          </div>
                          <Badge variant="secondary">Current</Badge>
                        </div>
                        <Button
                          variant="outline"
                          className="w-full bg-transparent"
                        >
                          Sign out of all other sessions
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </div>
              )}

              {/* Notifications Tab */}
              {tab === "notifications" && (
                <div className="space-y-6">
                  <Card>
                    <CardHeader>
                      <CardTitle>Email Notifications</CardTitle>
                      <CardDescription>
                        Configure your email notification preferences
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Booking Notifications</p>
                          <p className="text-sm text-muted-foreground">
                            Receive emails for new bookings and cancellations
                          </p>
                        </div>
                        <Switch
                          checked={notifications.emailBookings}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              emailBookings: checked,
                            })
                          }
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Payment Notifications</p>
                          <p className="text-sm text-muted-foreground">
                            Receive emails for payment updates and withdrawals
                          </p>
                        </div>
                        <Switch
                          checked={notifications.emailPayments}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              emailPayments: checked,
                            })
                          }
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Marketing Emails</p>
                          <p className="text-sm text-muted-foreground">
                            Receive promotional emails and platform updates
                          </p>
                        </div>
                        <Switch
                          checked={notifications.emailMarketing}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              emailMarketing: checked,
                            })
                          }
                        />
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>SMS Notifications</CardTitle>
                      <CardDescription>
                        Configure your SMS notification preferences
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Booking SMS</p>
                          <p className="text-sm text-muted-foreground">
                            Receive SMS for new bookings
                          </p>
                        </div>
                        <Switch
                          checked={notifications.smsBookings}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              smsBookings: checked,
                            })
                          }
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Payment SMS</p>
                          <p className="text-sm text-muted-foreground">
                            Receive SMS for payment confirmations
                          </p>
                        </div>
                        <Switch
                          checked={notifications.smsPayments}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              smsPayments: checked,
                            })
                          }
                        />
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>Push Notifications</CardTitle>
                      <CardDescription>
                        Configure browser push notifications
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">
                            Enable Push Notifications
                          </p>
                          <p className="text-sm text-muted-foreground">
                            Receive instant notifications in your browser
                          </p>
                        </div>
                        <Switch
                          checked={notifications.pushNotifications}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              pushNotifications: checked,
                            })
                          }
                        />
                      </div>
                    </CardContent>
                  </Card>

                  <div className="flex justify-end">
                    <Button onClick={handleNotificationSave}>
                      <Save className="h-4 w-4 mr-2" />
                      Save Preferences
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </Suspense>
    </HotelPageWrapper>
  );
}

export default ManageProfileClientPage;
