﻿"use client";

import type React from "react";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { AgentHeader } from "@/roles/agent/components/agent-header";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  changePasswordAction,
  changeProfileImageAction,
  getProfileAction,
  updateProfileAction,
} from "@/features/users/actions/profile-actions";
import { getStorageUrl } from "@/lib/utils";
import { customerProfileSchema } from "@/lib/validations/profile";
import type { User } from "@/core/api/services/auth/auth.types";
import {
  User as UserIcon,
  Mail,
  Phone,
  Camera,
  Lock,
  Save,
  Eye,
  EyeOff,
  CheckCircle2,
  Loader2,
} from "lucide-react";
import { toast } from "sonner";
import { Cropper, type CropperRef } from "react-advanced-cropper";

const AGENT_PROFILE_IMAGE_UPDATED_EVENT = "agent-profile-image-updated";

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

  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}`;
}

export default function ManageProfilePage() {
  const router = useRouter();
  const cropperRef = useRef<CropperRef>(null);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // Profile form state
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const [isUpdatingProfile, setIsUpdatingProfile] = useState(false);
  const [isUpdatingProfileImage, setIsUpdatingProfileImage] = useState(false);
  const [cropperOpen, setCropperOpen] = useState(false);
  const [cropSource, setCropSource] = useState<string | null>(null);

  // Password form 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 [isUpdatingPassword, setIsUpdatingPassword] = useState(false);

  // Derived state for header
  const agentName =
    firstName && lastName ? `${firstName} ${lastName}` : "Agent";
  // If email is empty (loading), use a placeholder or empty string
  const agentEmail = email || "info@ameeraholidays.com";

  useEffect(() => {
    const fetchProfile = async () => {
      try {
        const { success, data } = await getProfileAction();
        if (success && data) {
          const userData = data;
          setUser(userData);
          setFirstName(userData.first_name || "");
          setLastName(userData.last_name || "");
          setEmail(userData.email || "");
          setPhone(userData.phone_number || "");
          setProfileImage(getProfileImageSrc(userData.profile_image));
        } else {
          router.push("/login");
        }
      } catch (error) {
        console.error("Failed to fetch profile", error);
        toast.error("Failed to load profile data");
      } finally {
        setIsLoading(false);
      }
    };

    fetchProfile();
  }, [router]);

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

    if (!file) {
      return;
    }

    const allowedTypes = new Set(["image/jpeg", "image/jpg", "image/png"]);
    const extension = file.name.split(".").pop()?.toLowerCase();
    const allowedExtensions = new Set(["jpg", "jpeg", "png"]);
    const isAllowedImage =
      allowedTypes.has(file.type.toLowerCase()) ||
      (!!extension && allowedExtensions.has(extension));

    if (!isAllowedImage) {
      toast.error("Please upload a JPG, JPEG, or PNG image.");
      return;
    }

    const maxSizeInBytes = 5 * 1024 * 1024;
    if (file.size > maxSizeInBytes) {
      toast.error("Please upload an image under 5MB.");
      return;
    }

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

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

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

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

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

    const result = await changeProfileImageAction(formData);

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

    return result.data;
  };

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

    if (updatedProfile.success && updatedProfile.data) {
      setUser(updatedProfile.data);
      const updatedProfileImage = getProfileImageSrc(
        updatedProfile.data.profile_image,
        Date.now()
      );

      if (updatedProfileImage) {
        setProfileImage(updatedProfileImage);
        return updatedProfileImage;
      }
    }

    return null;
  };

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

    if (!canvas) {
      toast.error("Unable to crop image. Please try another image.");
      return;
    }

    const previousImage = profileImage;
    setIsUpdatingProfileImage(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 previewUrl = URL.createObjectURL(blob);

      setProfileImage(previewUrl);

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

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

        if (refreshedProfileImage) {
          window.dispatchEvent(
            new CustomEvent(AGENT_PROFILE_IMAGE_UPDATED_EVENT, {
              detail: { profileImage: refreshedProfileImage },
            })
          );
        }
      }

      URL.revokeObjectURL(previewUrl);
      setCropperOpen(false);
      if (cropSource) {
        URL.revokeObjectURL(cropSource);
        setCropSource(null);
      }
      toast.success("Profile photo updated successfully!");
    } catch (error) {
      console.error("[AgentProfile] Image upload failed", error);
      setProfileImage(previousImage);
      toast.error(
        error instanceof Error
          ? error.message
          : "Failed to update profile photo."
      );
    } finally {
      setIsUpdatingProfileImage(false);
    }
  };

  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsUpdatingProfile(true);

    try {
      console.log("[AgentProfile] Submitting profile update", {
        firstName,
        lastName,
        phone,
      });

      const updateData = {
        first_name: firstName,
        last_name: lastName,
        phone_number: phone,
      };

      console.log("[AgentProfile] Prepared update data", updateData);

      // Use Zod for robust validation
      const validation = customerProfileSchema.safeParse(updateData);

      if (!validation.success) {
        const firstError = validation.error.errors[0].message;
        console.warn(
          "[AgentProfile] Validation failed",
          validation.error.format()
        );
        toast.error(firstError);
        setIsUpdatingProfile(false);
        return;
      }

      console.log("[AgentProfile] Calling updateProfileAction");
      const result = await updateProfileAction(updateData);
      console.log("[AgentProfile] Update result", result);

      if (result.success) {
        toast.success("Profile updated successfully!");
      } else {
        toast.error(result.error || "Failed to update profile");
      }
    } catch (error) {
      console.error("[AgentProfile] Update failed", error);
      toast.error("An unexpected error occurred");
    } finally {
      setIsUpdatingProfile(false);
    }
  };

  const handleUpdatePassword = async (e: React.FormEvent) => {
    e.preventDefault();

    if (newPassword !== confirmPassword) {
      toast.error("New passwords do not match");
      return;
    }

    if (newPassword.length < 8) {
      toast.error("Password must be at least 8 characters");
      return;
    }

    setIsUpdatingPassword(true);

    try {
      const result = await changePasswordAction({
        password: currentPassword,
        new_password: newPassword,
        new_password_confirmation: confirmPassword,
      });

      if (!result.success) {
        toast.error(result.error || "Failed to update password");
        return;
      }

      toast.success("Password updated successfully!");
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
    } catch (error) {
      console.error(error);
      toast.error(
        error instanceof Error ? error.message : "Failed to update password"
      );
    } finally {
      setIsUpdatingPassword(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-500" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <AgentHeader agentEmail={agentEmail} agentName={agentName} />
      <main className="container mx-auto p-4 md:p-6 lg:p-8 max-w-4xl">
        <div className="mb-8">
          <h1 className="text-2xl font-bold">Manage Profile</h1>
          <p className="text-muted-foreground">
            Update your profile information and password
          </p>
        </div>

        <div className="space-y-6">
          {/* Profile Photo Section */}
          <Card className="border-border/50">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Camera className="h-5 w-5 text-teal-600" />
                Profile Photo
              </CardTitle>
              <CardDescription>
                Upload a profile photo to personalize your account
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-6">
                <Avatar className="h-24 w-24 border-4 border-teal-100">
                  <AvatarImage
                    src={profileImage || undefined}
                    alt={agentName}
                  />
                  <AvatarFallback className="bg-gradient-to-br from-teal-500 to-teal-600 text-white text-2xl">
                    {firstName && lastName
                      ? `${firstName[0]}${lastName[0]}`.toUpperCase()
                      : "AG"}
                  </AvatarFallback>
                </Avatar>
                <div className="space-y-2">
                  <Label htmlFor="photo" className="cursor-pointer">
                    <div
                      className={`inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-teal-600 text-white transition-colors ${
                        isUpdatingProfileImage
                          ? "opacity-70 cursor-not-allowed"
                          : "hover:bg-teal-700"
                      }`}
                    >
                      {isUpdatingProfileImage ? (
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
                      ) : (
                        <Camera className="h-4 w-4" />
                      )}
                      {isUpdatingProfileImage ? "Uploading..." : "Upload Photo"}
                    </div>
                  </Label>
                  <Input
                    id="photo"
                    type="file"
                    accept="image/*"
                    className="hidden"
                    disabled={isUpdatingProfileImage}
                    onChange={handleImageUpload}
                  />
                  <p className="text-xs text-muted-foreground">
                    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 agent 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={isUpdatingProfileImage}
                >
                  Cancel
                </Button>
                <Button
                  type="button"
                  onClick={handleCropAndUpload}
                  disabled={isUpdatingProfileImage}
                  className="bg-teal-600 hover:bg-teal-700 text-white"
                >
                  {isUpdatingProfileImage && (
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  )}
                  {isUpdatingProfileImage ? "Uploading..." : "Crop & Upload"}
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>

          {/* Profile Information Section */}
          <Card className="border-border/50">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <UserIcon className="h-5 w-5 text-teal-600" />
                Profile Information
              </CardTitle>
              <CardDescription>Update your personal details</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleUpdateProfile} className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="firstName">First Name</Label>
                    <div className="relative">
                      <UserIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        id="firstName"
                        value={firstName}
                        onChange={(e) => setFirstName(e.target.value)}
                        className="pl-10"
                        placeholder="First Name"
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="lastName">Last Name</Label>
                    <div className="relative">
                      <UserIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        id="lastName"
                        value={lastName}
                        onChange={(e) => setLastName(e.target.value)}
                        className="pl-10"
                        placeholder="Last Name"
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="email">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
                        id="email"
                        type="email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        className="pl-10"
                        placeholder="Enter your email"
                        disabled
                      />
                    </div>
                    <p className="text-xs text-muted-foreground">
                      Email cannot be changed
                    </p>
                  </div>
                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="phone">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
                        id="phone"
                        type="tel"
                        value={phone}
                        onChange={(e) => setPhone(e.target.value)}
                        className="pl-10"
                        placeholder="Enter your phone number"
                      />
                    </div>
                  </div>
                </div>
                <div className="flex justify-end">
                  <Button
                    type="submit"
                    className="bg-teal-600 hover:bg-teal-700 text-white"
                    disabled={isUpdatingProfile}
                  >
                    {isUpdatingProfile ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
                        Saving...
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4 mr-2" />
                        Save Changes
                      </>
                    )}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>

          {/* Password Section */}
          <Card className="border-border/50">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Lock className="h-5 w-5 text-teal-600" />
                Change Password
              </CardTitle>
              <CardDescription>Update your account password</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleUpdatePassword} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="currentPassword">Current Password</Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="currentPassword"
                      type={showCurrentPassword ? "text" : "password"}
                      value={currentPassword}
                      onChange={(e) => setCurrentPassword(e.target.value)}
                      className="pl-10 pr-10"
                      placeholder="Enter current password"
                    />
                    <button
                      type="button"
                      onClick={() =>
                        setShowCurrentPassword(!showCurrentPassword)
                      }
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    >
                      {showCurrentPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </button>
                  </div>
                </div>

                <Separator />

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="newPassword">New Password</Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        id="newPassword"
                        type={showNewPassword ? "text" : "password"}
                        value={newPassword}
                        onChange={(e) => setNewPassword(e.target.value)}
                        className="pl-10 pr-10"
                        placeholder="Enter new password"
                      />
                      <button
                        type="button"
                        onClick={() => setShowNewPassword(!showNewPassword)}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                      >
                        {showNewPassword ? (
                          <EyeOff className="h-4 w-4" />
                        ) : (
                          <Eye className="h-4 w-4" />
                        )}
                      </button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="confirmPassword">
                      Confirm New Password
                    </Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        id="confirmPassword"
                        type={showConfirmPassword ? "text" : "password"}
                        value={confirmPassword}
                        onChange={(e) => setConfirmPassword(e.target.value)}
                        className="pl-10 pr-10"
                        placeholder="Confirm new password"
                      />
                      <button
                        type="button"
                        onClick={() =>
                          setShowConfirmPassword(!showConfirmPassword)
                        }
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                      >
                        {showConfirmPassword ? (
                          <EyeOff className="h-4 w-4" />
                        ) : (
                          <Eye className="h-4 w-4" />
                        )}
                      </button>
                    </div>
                  </div>
                </div>

                {/* Password requirements */}
                <div className="bg-muted/50 rounded-lg p-4">
                  <p className="text-sm font-medium mb-2">
                    Password Requirements:
                  </p>
                  <ul className="text-sm text-muted-foreground space-y-1">
                    <li className="flex items-center gap-2">
                      <CheckCircle2
                        className={`h-4 w-4 ${newPassword.length >= 8 ? "text-green-500" : "text-muted-foreground"}`}
                      />
                      At least 8 characters
                    </li>
                    <li className="flex items-center gap-2">
                      <CheckCircle2
                        className={`h-4 w-4 ${/[A-Z]/.test(newPassword) ? "text-green-500" : "text-muted-foreground"}`}
                      />
                      One uppercase letter
                    </li>
                    <li className="flex items-center gap-2">
                      <CheckCircle2
                        className={`h-4 w-4 ${/[0-9]/.test(newPassword) ? "text-green-500" : "text-muted-foreground"}`}
                      />
                      One number
                    </li>
                    <li className="flex items-center gap-2">
                      <CheckCircle2
                        className={`h-4 w-4 ${
                          newPassword === confirmPassword &&
                          newPassword.length > 0
                            ? "text-green-500"
                            : "text-muted-foreground"
                        }`}
                      />
                      Passwords match
                    </li>
                  </ul>
                </div>

                <div className="flex justify-end">
                  <Button
                    type="submit"
                    className="bg-teal-600 hover:bg-teal-700 text-white"
                    disabled={
                      isUpdatingPassword ||
                      !currentPassword ||
                      !newPassword ||
                      !confirmPassword
                    }
                  >
                    {isUpdatingPassword ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
                        Updating...
                      </>
                    ) : (
                      <>
                        <Lock className="h-4 w-4 mr-2" />
                        Update Password
                      </>
                    )}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </div>
      </main>
    </div>
  );
}
