"use client";

import type React from "react";

import { useEffect, useState, useRef } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { Camera, Loader2, Save, UserRound } from "lucide-react";
import { customerProfileSchema } from "@/lib/validations/profile";
import { Cropper, type CropperRef } from "react-advanced-cropper";
import {
  changeProfileImageAction,
  getProfileAction,
  updateProfileAction,
} from "@/features/users/actions/profile-actions";
import type { User } from "@/core/api/services/auth/auth.types";
import { getStorageUrl } from "@/lib/utils";

type ProfileActionResult = Awaited<ReturnType<typeof getProfileAction>>;

let profileRequest: Promise<ProfileActionResult> | null = null;
const USER_PROFILE_IMAGE_UPDATED_EVENT = "user-profile-image-updated";

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

function normalizeValue(value: string | number | null | undefined) {
  return value === null || value === undefined ? "" : String(value);
}

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

function formatDateTime(value: string | null | undefined) {
  if (!value) {
    return "";
  }

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return new Intl.DateTimeFormat("en-IN", {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(date);
}

function hydrateProfile(userData: User) {
  return {
    firstName: normalizeText(userData.first_name),
    lastName: normalizeText(userData.last_name),
    email: normalizeText(userData.email),
    phone: normalizeText(userData.phone_number),
    address: normalizeText(userData.address),
    profileImage: getProfileImageSrc(userData.profile_image),
    details: {
      userId: normalizeValue(userData.id),
      officeAddress: normalizeText(userData.office_address),
      gstNumber: normalizeText(userData.gst_number),
      panNumber: normalizeText(userData.pan_number),
      licenseNumber: normalizeText(userData.license_number),
      gstCertificate: normalizeText(userData.gst_certificate),
      panDocument: normalizeText(userData.pan_document),
      licenseDocument: normalizeText(userData.license_document),
      msmeCertificate: normalizeText(userData.msme_certificate),
      businessDocument: normalizeText(userData.business_document),
      status: normalizeText(userData.status),
      reasonForReject: normalizeText(userData.reason_for_reject),
      reasonForBlock: normalizeText(userData.reason_for_block),
      roleName: normalizeText(userData.user_role?.role?.role_name),
      roleSlug: normalizeText(userData.user_role?.role?.slug),
      emailVerifiedAt: formatDateTime(userData.email_verified_at),
      createdBy: normalizeValue(userData.created_by),
      updatedBy: normalizeValue(userData.updated_by),
      createdAt: formatDateTime(userData.created_at),
      updatedAt: formatDateTime(userData.updated_at),
      deletedAt: formatDateTime(userData.deleted_at),
    },
  };
}

function loadProfile(options: { forceRefresh?: boolean } = {}) {
  if (options.forceRefresh || !profileRequest) {
    profileRequest = getProfileAction().then(
      (result) => {
        if (!result.success) {
          profileRequest = null;
        }

        return result;
      },
      (error) => {
        profileRequest = null;
        throw error;
      }
    );
  }

  return profileRequest;
}

export function ManageProfileContent() {
  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 [address, setAddress] = useState("");
  const [officeAddress, setOfficeAddress] = useState("");
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const [cropperOpen, setCropperOpen] = useState(false);
  const [cropSource, setCropSource] = useState<string | null>(null);
  const [isUploadingProfileImage, setIsUploadingProfileImage] = useState(false);
  const [isUpdating, setIsUpdating] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const cropperRef = useRef<CropperRef>(null);
  const toast = useToastEnhanced();

  // Derived state
  const _userName =
    firstName && lastName ? `${firstName} ${lastName}` : firstName || "User";
  const userInitials =
    firstName && lastName
      ? `${firstName[0]}${lastName[0]}`.toUpperCase()
      : firstName
        ? firstName[0].toUpperCase()
        : "U";

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

    const fetchProfile = async () => {
      try {
        const { success, data } = await loadProfile();

        if (!isActive) {
          return;
        }

        if (success && data) {
          const profile = hydrateProfile(data);
          setUser(data);
          setFirstName(profile.firstName);
          setLastName(profile.lastName);
          setEmail(profile.email);
          setPhone(profile.phone);
          setAddress(profile.address);
          setOfficeAddress(profile.details.officeAddress);
          setProfileImage(profile.profileImage);
        } else {
          // Fallback or redirect
          // router.push("/login") // Optional
        }
      } catch (error) {
        console.error("Failed to fetch profile", error);
        toast.error({
          title: "Error",
          description: "Failed to load profile data",
        });
      } finally {
        if (isActive) {
          setIsLoading(false);
        }
      }
    };

    fetchProfile();

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

  useEffect(() => {
    return () => {
      if (cropSource?.startsWith("blob:")) {
        URL.revokeObjectURL(cropSource);
      }
    };
  }, [cropSource]);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsUpdating(true);

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

      // Prepare form values (trim whitespace)
      const trimmedFirstName = firstName.trim();
      const trimmedLastName = lastName.trim();
      const trimmedPhone = phone.trim();
      const trimmedAddress = address.trim();
      const trimmedOfficeAddress = officeAddress.trim();

      // Merge form data with existing user data to ensure required fields are always present
      // Use form values if provided, otherwise fall back to existing user data
      const finalFirstName = trimmedFirstName || user?.first_name || "";
      const finalLastName = trimmedLastName || user?.last_name || "";
      const finalPhone = trimmedPhone || user?.phone_number || "";

      const updateData = {
        first_name: finalFirstName,
        last_name: finalLastName,
        phone_number: finalPhone,
        address: trimmedAddress || undefined,
        office_address: trimmedOfficeAddress || undefined,
      };

      console.log("[ManageProfile] 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(
          "[ManageProfile] Validation failed",
          validation.error.format()
        );
        toast.error({
          title: "Validation Error",
          description: firstError,
        });
        setIsUpdating(false);
        return;
      }

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

      if (result.success) {
        const nextUser = user
          ? {
              ...user,
              first_name: finalFirstName,
              last_name: finalLastName,
              phone_number: finalPhone,
              address: trimmedAddress || null,
              office_address: trimmedOfficeAddress || null,
            }
          : null;

        if (nextUser) {
          setUser(nextUser);
          profileRequest = Promise.resolve({
            success: true,
            data: nextUser,
          });
        }

        setFirstName(finalFirstName);
        setLastName(finalLastName);
        setPhone(finalPhone);
        setAddress(trimmedAddress);
        setOfficeAddress(trimmedOfficeAddress);
        toast.success({
          title: "Profile updated",
          description: "Your profile has been successfully updated.",
        });
      } else {
        toast.error({
          title: "Error",
          description: result.error || "Failed to update profile",
        });
      }
    } catch (error) {
      console.error(error);
      toast.error({
        title: "Error",
        description: "An unexpected error occurred",
      });
    } finally {
      setIsUpdating(false);
    }
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (!file.type.startsWith("image/")) {
        toast.error({
          title: "Invalid file type",
          description: "Please select a valid image file",
        });
        return;
      }

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

      const objectUrl = URL.createObjectURL(file);
      setCropSource(objectUrl);
      setCropperOpen(true);
    }
  };

  const handleRemoveProfileImage = () => {
    setProfileImage(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

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

    const result = await changeProfileImageAction(formData);

    if (!result.success) {
      toast.error({
        title: "Upload failed",
        description: result.error || "Failed to update profile image",
      });
      return null;
    }

    return result.data;
  };

  const refreshProfileImage = async () => {
    profileRequest = null;
    const result = await loadProfile({ forceRefresh: true });

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

      setUser(result.data);
      setFirstName(hydrated.firstName);
      setLastName(hydrated.lastName);
      setEmail(hydrated.email);
      setPhone(hydrated.phone);
      setAddress(hydrated.address);
      setOfficeAddress(hydrated.details.officeAddress);
      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;
    }

    setIsUploadingProfileImage(true);

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

      if (!blob) {
        toast.error({
          title: "Crop failed",
          description: "Unable to generate cropped image.",
        });
        return;
      }

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

      const uploadedImage = await uploadProfileImage(croppedFile);
      if (uploadedImage === null) {
        return;
      }

      const localPreview = URL.createObjectURL(blob);

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

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

        if (refreshedProfileImage) {
          URL.revokeObjectURL(localPreview);
          window.dispatchEvent(
            new CustomEvent(USER_PROFILE_IMAGE_UPDATED_EVENT, {
              detail: { profileImage: refreshedProfileImage },
            })
          );
        }
      }

      setCropperOpen(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }

      toast.success({
        title: "Photo uploaded",
        description: "Your profile photo has been updated",
      });
    } catch (error) {
      console.error("Profile image upload failed", error);
      toast.error({
        title: "Upload failed",
        description: "An unexpected error occurred while uploading image.",
      });
    } finally {
      setIsUploadingProfileImage(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex justify-center p-8">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Card className="w-full overflow-hidden rounded-2xl border-border/50 bg-white shadow-md">
        <CardHeader className="border-b border-border/50 px-8 py-7">
          <div className="flex items-center gap-4">
            <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-teal-600 to-cyan-600 text-white shadow-md">
              <UserRound className="h-5 w-5" />
            </div>
            <div>
              <CardTitle className="text-2xl font-bold text-gray-900">
                Manage Profile
              </CardTitle>
              <CardDescription className="mt-1 text-sm text-gray-600">
                Update your personal information
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="px-8 py-7">
          <div className="flex flex-col gap-5 border-b border-border/50 pb-7 sm:flex-row sm:items-center">
            <div className="relative w-fit shrink-0">
              <Avatar className="h-24 w-24 border-2 border-white shadow-lg ring-1 ring-border/60">
              {profileImage ? (
                <AvatarImage
                  src={profileImage || "/placeholder.png"}
                  alt="Profile"
                  className="object-cover"
                />
              ) : (
                <AvatarFallback className="bg-teal-50 text-2xl font-semibold text-teal-700">
                  {userInitials}
                </AvatarFallback>
              )}
            </Avatar>
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="absolute -bottom-1 -right-1 flex h-9 w-9 items-center justify-center rounded-full bg-gradient-to-br from-teal-600 to-cyan-600 text-white shadow-md transition hover:from-teal-700 hover:to-cyan-700"
                aria-label="Upload profile photo"
              >
                <Camera className="h-4 w-4" />
              </button>
            </div>
            <div className="min-w-0 space-y-3">
              <div>
                <h2 className="font-bold text-gray-900">Profile Photo</h2>
                <p className="mt-1 text-sm text-gray-600">
                  JPG, PNG or GIF. Max size 5MB.
                </p>
              </div>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                onChange={handleImageChange}
                className="hidden"
                aria-label="Upload profile photo"
              />
              <div className="flex flex-wrap gap-2">
                <Button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="h-10 rounded-lg bg-gradient-to-r from-teal-600 to-cyan-600 px-5 font-bold text-white shadow-md hover:from-teal-700 hover:to-cyan-700"
                >
                  Upload New
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleRemoveProfileImage}
                  className="h-10 rounded-lg bg-transparent"
                >
                  Remove
                </Button>
              </div>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="mt-7 space-y-5">
            <div>
              <h2 className="text-lg font-bold text-gray-900">
                Personal Information
              </h2>
              <p className="mt-1 text-sm text-gray-600">
                Update your profile details here
              </p>
            </div>

            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="firstName" className="text-xs font-bold text-gray-800">
                  First Name
                </Label>
                <Input
                  id="firstName"
                  value={firstName}
                  onChange={(e) => setFirstName(e.target.value)}
                  disabled={isUpdating}
                  className="h-12 rounded-xl border-border/60 bg-teal-50/30 shadow-none focus-visible:border-teal-500 focus-visible:ring-teal-100"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="lastName" className="text-xs font-bold text-gray-800">
                  Last Name
                </Label>
                <Input
                  id="lastName"
                  value={lastName}
                  onChange={(e) => setLastName(e.target.value)}
                  disabled={isUpdating}
                  className="h-12 rounded-xl border-border/60 bg-teal-50/30 shadow-none focus-visible:border-teal-500 focus-visible:ring-teal-100"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="email" className="text-xs font-bold text-gray-800">
                  Email
                </Label>
                <Input
                  id="email"
                  type="email"
                  value={email}
                  disabled
                  className="h-12 rounded-xl border-border/60 bg-gray-50 shadow-none"
                />
                <p className="text-xs text-gray-500">Email cannot be changed</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="phone" className="text-xs font-bold text-gray-800">
                  Phone Number
                </Label>
                <Input
                  id="phone"
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="+91 9876543210"
                  disabled={isUpdating}
                  className="h-12 rounded-xl border-border/60 bg-teal-50/30 shadow-none placeholder:text-gray-400 focus-visible:border-teal-500 focus-visible:ring-teal-100"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="address" className="text-xs font-bold text-gray-800">
                  Address
                </Label>
                <Input
                  id="address"
                  type="text"
                  value={address}
                  onChange={(e) => setAddress(e.target.value)}
                  placeholder="Enter your address"
                  disabled={isUpdating}
                  className="h-12 rounded-xl border-border/60 bg-teal-50/30 shadow-none placeholder:text-gray-400 focus-visible:border-teal-500 focus-visible:ring-teal-100"
                />
              </div>

              <div className="space-y-2">
                <Label
                  htmlFor="officeAddress"
                  className="text-xs font-bold text-gray-800"
                >
                  Office Address
                </Label>
                <Input
                  id="officeAddress"
                  type="text"
                  value={officeAddress}
                  onChange={(e) => setOfficeAddress(e.target.value)}
                  placeholder="Enter your office address"
                  disabled={isUpdating}
                  className="h-12 rounded-xl border-border/60 bg-teal-50/30 shadow-none placeholder:text-gray-400 focus-visible:border-teal-500 focus-visible:ring-teal-100"
                />
              </div>
            </div>

            <div className="flex justify-end border-t border-border/50 pt-6">
              <Button
                type="submit"
                disabled={isUpdating}
                className="h-12 w-full gap-2 rounded-xl bg-gradient-to-r from-teal-600 to-cyan-600 px-8 font-bold text-white shadow-md hover:from-teal-700 hover:to-cyan-700 hover:shadow-lg md:w-auto"
              >
                {isUpdating ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Saving...
                  </>
                ) : (
                  <>
                    <Save className="h-4 w-4" />
                    Save Changes
                  </>
                )}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>

      <Dialog open={cropperOpen} onOpenChange={setCropperOpen}>
        <DialogContent className="sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>Crop Profile Photo</DialogTitle>
            <DialogDescription>
              Adjust your image and upload it as 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={() => setCropperOpen(false)}
              disabled={isUploadingProfileImage}
            >
              Cancel
            </Button>
            <Button
              type="button"
              onClick={handleCropAndUpload}
              disabled={isUploadingProfileImage}
            >
              {isUploadingProfileImage && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              {isUploadingProfileImage ? "Uploading..." : "Crop & Upload"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

    </div>
  );
}
