"use client";

import { useState, useRef, useEffect } from "react";
import { toast } from "sonner";
import { Eye, X, EyeOff, Upload, Pencil } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "../../../../../../../src/components/ui/dialog";
import { Button } from "../../../../../../../src/components/ui/button";
import { useAppDispatch, useAppSelector } from "@/hooks/redux";
import {
  loginStart,
  loginSuccess,
  loginFailure,
  reset,
  clearError,
} from "@/lib/authSlice";

interface AdminProfile {
  _id?: string;
  name: string;
  email: string;
  phone: string;
  username: string;
  avatar?: string;
  passwordChangedAt?: Date | null | undefined;
}

export default function ProfilePageDetails() {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [saving, setSaving] = useState(false);
  const [updatingPass, setUpdatingPass] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isPassOpen, setIsPassOpen] = useState(false);
  const dispatch = useAppDispatch();
  const [profile, setProfile] = useState<AdminProfile>({
    name: "Admin User",
    email: "admin@dulhesahab.com",
    phone: "+91 9000000000",
    username: "Admin User",
    avatar: "",
    passwordChangedAt: null,
  });

  const [dataLoading, setDataLoading] = useState(false);
  const [editForm, setEditForm] = useState<AdminProfile>(profile);
  const [validationError, setValidationError] = useState({
    name: null as string | null,
    email: null as string | null,
    phone: null as string | null,
  });

  const [touched, setTouched] = useState({
    name: false,
    email: false,
    phone: false,
  });

  const [passForm, setPassForm] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });

  const [showPass, setShowPass] = useState({
    current: false,
    new: false,
    confirm: false,
  });

  const [strength, setStrength] = useState({ score: 0, label: "", color: "" });

  useEffect(() => {
    fetchProfile();
  }, []);

  const fetchProfile = async () => {
    setDataLoading(true);
    try {
      const res = await fetch("/api/profile");
      const data = await res.json();
      if (data.success) {
        setProfile(data.data);
        setEditForm(data.data);
      }
    } catch {
      toast.error("Failed to load profile");
    } finally {
      setDataLoading(false);
    }
  };

  const getInitials = () => {
    const [first, last] = profile?.name?.split(" ") || [];
    const firstChar = first?.[0] || "";
    const lastChar = last?.[0] || "";
    return (firstChar + lastChar).toUpperCase() || "AD";
  };

  const resetForm = () => {
    setAvatarFile(null);
    setAvatarPreview(null);
  };

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 2 * 1024 * 1024) {
      toast.error("Image must be under 2MB");
      return;
    }
    setAvatarFile(file);
    setAvatarPreview(URL.createObjectURL(file));
  };

  // Enhanced validation function
  const validateField = (key: string, value: string): string | null => {
    let error = null;

    switch (key) {
      case "name": {
        const trimmed = value.trim();
        if (!trimmed) {
          error = "Name is required";
        } else if (trimmed.length < 2) {
          error = "Name must be at least 2 characters";
        } else if (trimmed.length > 50) {
          error = "Name must be less than 50 characters";
        } else if (!/^[a-zA-Z\s\-']+$/.test(trimmed)) {
          error =
            "Name can only contain letters, spaces, hyphens, and apostrophes";
        }
        break;
      }

      case "email": {
        const trimmed = value.trim();
        if (!trimmed) {
          error = "Email is required";
        } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
          error = "Please enter a valid email address";
        } else if (trimmed.length > 100) {
          error = "Email must be less than 100 characters";
        }
        break;
      }

      case "phone": {
        const trimmed = value.trim();
        if (!trimmed) {
          error = "Phone number is required";
        } else {
          // Remove any non-digit characters for validation
          const digitsOnly = trimmed.replace(/\D/g, "");

          // Check if it's a valid Indian phone number
          if (digitsOnly.length !== 10) {
            error = "Phone number must be exactly 10 digits";
          } else if (!/^[6-9]\d{9}$/.test(digitsOnly)) {
            error = "Invalid Indian phone number (must start with 6,7,8, or 9)";
          }
        }
        break;
      }

      default:
        error = null;
    }

    return error;
  };

  // Update validation on field change
  const handleFieldChange = (key: string, value: string) => {
    setEditForm((prev) => ({
      ...prev,
      [key]: value,
    }));

    // Validate on change
    const error = validateField(key, value);
    setValidationError((prev) => ({
      ...prev,
      [key]: error,
    }));

    // Mark as touched
    setTouched((prev) => ({
      ...prev,
      [key]: true,
    }));
  };

  // Check if form is valid
  const isFormValid = () => {
    const nameError = validateField("name", editForm.name);
    const emailError = validateField("email", editForm.email);
    const phoneError = validateField("phone", editForm.phone);

    // Update validation errors
    setValidationError({
      name: nameError,
      email: emailError,
      phone: phoneError,
    });

    // Mark all fields as touched
    setTouched({
      name: true,
      email: true,
      phone: true,
    });

    return !nameError && !emailError && !phoneError;
  };

  // For backward compatibility with existing checkValidation function
  const checkValidation = (key: string, value: any) => {
    const error = validateField(key, value);
    setValidationError((prev: any) => ({
      ...prev,
      [key]: error,
    }));
    return error;
  };

  const handleSaveProfile = async () => {
    // Validate all fields before saving
    if (!isFormValid()) {
      toast.error("Please fix all validation errors");
      return;
    }

    setSaving(true);
    try {
      const formData = new FormData();
      Object.entries(editForm).forEach(([k, v]) => {
        if (k !== "avatar") {
          formData.append(k, v || "");
        }
      });

      if (avatarFile) {
        formData.append("avatar", avatarFile);
      } else {
        formData.append("avatar", editForm.avatar || "");
      }

      const res = await fetch(`/api/profile/${editForm?._id}`, {
        method: "PUT",
        body: formData,
      });
      const data = await res.json();
      if (data.success) {
        toast.success("Profile updated successfully");
        setProfile(editForm);
        setAvatarFile(null);
        fetchProfile();
        dispatch(reset({ user: data.data }));
        setIsEditOpen(false);
        // Reset touched states
        setTouched({ name: false, email: false, phone: false });
      } else {
        toast.error(data.error || "Failed to update profile");
      }
    } catch {
      toast.error("Something went wrong");
    } finally {
      setSaving(false);
    }
  };

  const checkStrength = (val: string) => {
    let score = 0;
    if (val.length >= 8) score++;
    if (/[A-Z]/.test(val)) score++;
    if (/[0-9]/.test(val)) score++;
    if (/[^A-Za-z0-9]/.test(val)) score++;
    const map = [
      { label: "", color: "" },
      { label: "Weak", color: "#E24B4A" },
      { label: "Fair", color: "#EF9F27" },
      { label: "Good", color: "#378ADD" },
      { label: "Strong", color: "#639922" },
    ];
    setStrength({ score, ...map[score] });
  };

  const handleUpdatePassword = async () => {
    const { currentPassword, newPassword, confirmPassword } = passForm;
    if (!currentPassword || !newPassword || !confirmPassword) {
      toast.error("All fields are required");
      return;
    }
    if (currentPassword === newPassword) {
      toast.error("Current and new password should not be same");
      return;
    }
    if (newPassword !== confirmPassword) {
      toast.error("Passwords do not match");
      return;
    }
    if (newPassword.length < 6) {
      toast.error("Password must be at least 6 characters");
      return;
    }

    setUpdatingPass(true);
    try {
      const res = await fetch("/api/profile/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ currentPassword, newPassword }),
      });
      const data = await res.json();
      if (data.success) {
        toast.success("Password updated successfully");
        fetchProfile();
        setPassForm({
          currentPassword: "",
          newPassword: "",
          confirmPassword: "",
        });
        setStrength({ score: 0, label: "", color: "" });
        setIsPassOpen(false);
      } else {
        toast.error(data.error || "Failed to update password");
      }
    } catch {
      toast.error("Something went wrong");
    } finally {
      setUpdatingPass(false);
    }
  };

  const inputClass =
    "w-full px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-1 focus:ring-ring transition-colors";

  const getInputClass = (fieldName: string) => {
    const hasError =
      validationError[fieldName as keyof typeof validationError] &&
      touched[fieldName as keyof typeof touched];
    return `${inputClass} ${
      hasError
        ? "border-red-500 focus:ring-red-500"
        : "border-input focus:ring-ring"
    }`;
  };

  return (
    <div className="space-y-4">
      {/* Page header */}
      <div>
        <h1 className="text-2xl font-semibold">My profile</h1>
      </div>

      {/* Profile card — read only */}
      {dataLoading ? (
        <div className="flex h-64 items-center justify-center">Loading...</div>
      ) : (
        <div className="bg-card rounded-xl border">
          {/* Avatar + name banner */}
          <div className="flex items-center justify-between border-b px-6 py-3">
            <div className="flex items-center gap-4">
              {profile.avatar ? (
                <img
                  src={profile.avatar}
                  alt="Avatar"
                  className="h-16 w-16 rounded-full border object-cover"
                />
              ) : (
                <div
                  className="flex h-16 w-16 items-center justify-center rounded-full text-xl font-medium"
                  style={{ background: "#EEEDFE", color: "#3C3489" }}
                >
                  {getInitials()}
                </div>
              )}
              <div>
                <p className="text-lg font-medium">{profile.name}</p>
                <p className="text-muted-foreground text-sm">{profile.email}</p>
                <span
                  className="mt-1 inline-block rounded-full px-2.5 py-0.5 text-xs font-medium"
                  style={{ background: "#EEEDFE", color: "#3C3489" }}
                >
                  Admin
                </span>
              </div>
            </div>
            <Button
              onClick={() => {
                setEditForm(profile);
                setIsEditOpen(true);
                resetForm();
                // Reset validation states
                setValidationError({ name: null, email: null, phone: null });
                setTouched({ name: false, email: false, phone: false });
              }}
              variant="outline"
              size="sm"
              className="gap-2"
            >
              <Pencil className="h-3.5 w-3.5" />
              Edit profile
            </Button>
          </div>

          {/* Details grid */}
          <div className="grid grid-cols-2 gap-x-12 gap-y-5 px-6 py-4">
            {[
              { label: "Name", value: profile.name },
              { label: "Email address", value: profile.email },
              { label: "Phone number", value: profile.phone },
              { label: "Role", value: "Admin" },
            ].map(({ label, value }) => (
              <div key={label}>
                <p className="text-muted-foreground mb-1 text-xs">{label}</p>
                <p className="text-sm font-medium">{value || "—"}</p>
              </div>
            ))}
          </div>

          {/* Password row */}
          <div className="flex items-center justify-between border-t px-6 py-3">
            <div>
              <p className="text-sm font-medium">Password</p>
              <p className="text-muted-foreground mt-0.5 text-xs">
                Last changed:{" "}
                {profile?.passwordChangedAt
                  ? new Date(profile.passwordChangedAt).toLocaleString()
                  : "never"}
              </p>
            </div>
            <Button
              onClick={() => setIsPassOpen(true)}
              variant="outline"
              size="sm"
              className="gap-2"
            >
              <Pencil className="h-3.5 w-3.5" />
              Change password
            </Button>
          </div>
        </div>
      )}

      {/* ── Edit Profile Dialog ── */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent className="max-w-2xl">
          <div className="mx-auto my-2 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
            <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>Edit profile</DialogTitle>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    setIsEditOpen(false);
                    setValidationError({
                      name: null,
                      email: null,
                      phone: null,
                    });
                    setTouched({ name: false, email: false, phone: false });
                  }}
                />
              </DialogHeader>
              <div className="flex flex-grow flex-col p-4 pb-0 pl-2 pr-2">
                <div className="flex flex-1 flex-col pb-0">
                  <div className="max-h-[60vh] flex-1 overflow-y-auto pl-2 pr-2">
                    <div className="space-y-4">
                      {/* Avatar */}
                      <div className="flex items-center gap-4">
                        {avatarPreview || profile.avatar ? (
                          <img
                            src={avatarPreview || profile.avatar}
                            alt="Avatar"
                            className="h-14 w-14 rounded-full border object-cover"
                          />
                        ) : (
                          <div
                            className="flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-full text-lg font-medium"
                            style={{ background: "#EEEDFE", color: "#3C3489" }}
                          >
                            {getInitials()}
                          </div>
                        )}
                        <label className="text-muted-foreground hover:bg-muted/60 flex cursor-pointer items-center gap-2 rounded-md border px-3 py-2 text-sm transition-colors">
                          <Upload className="h-4 w-4" />
                          Upload photo
                          <input
                            ref={fileInputRef}
                            type="file"
                            accept="image/png,image/jpeg,image"
                            className="hidden"
                            onChange={handleAvatarChange}
                          />
                        </label>
                        <p className="text-muted-foreground text-xs">
                          PNG, JPG up to 2MB
                        </p>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        {/* Name Field */}
                        <div className="space-y-1.5">
                          <label className="text-muted-foreground text-xs">
                            Name <span className="text-red-500">*</span>
                          </label>
                          <input
                            className={getInputClass("name")}
                            value={editForm.name}
                            onChange={(e) => {
                              handleFieldChange("name", e.target.value);
                            }}
                            onBlur={() => {
                              setTouched((prev) => ({ ...prev, name: true }));
                              validateField("name", editForm.name);
                            }}
                            placeholder="Enter your full name"
                          />
                          {touched.name && validationError.name && (
                            <p className="mt-1 text-xs text-red-500">
                              {validationError.name}
                            </p>
                          )}
                        </div>

                        {/* Email Field */}
                        <div className="space-y-1.5">
                          <label className="text-muted-foreground text-xs">
                            Email address{" "}
                            <span className="text-red-500">*</span>
                          </label>
                          <input
                            type="email"
                            className={getInputClass("email")}
                            value={editForm.email}
                            onChange={(e) => {
                              handleFieldChange("email", e.target.value);
                            }}
                            onBlur={() => {
                              setTouched((prev) => ({ ...prev, email: true }));
                              validateField("email", editForm.email);
                            }}
                            placeholder="Enter your email"
                          />
                          {touched.email && validationError.email && (
                            <p className="mt-1 text-xs text-red-500">
                              {validationError.email}
                            </p>
                          )}
                        </div>
                      </div>

                      {/* Phone Field */}
                      <div className="grid grid-cols-1 gap-4">
                        <div className="space-y-1.5">
                          <label className="text-muted-foreground text-xs">
                            Phone number <span className="text-red-500">*</span>
                          </label>
                          <input
                            type="tel"
                            className={getInputClass("phone")}
                            value={editForm.phone}
                            onChange={(e) => {
                              // Allow only digits and + sign
                              const value = e.target.value.replace(
                                /[^0-9+]/g,
                                "",
                              );
                              handleFieldChange("phone", value);
                            }}
                            onBlur={() => {
                              setTouched((prev) => ({ ...prev, phone: true }));
                              validateField("phone", editForm.phone);
                            }}
                            placeholder="Enter 10-digit phone number"
                            maxLength={13} // +91 + 10 digits
                          />
                          {touched.phone && validationError.phone && (
                            <p className="mt-1 text-xs text-red-500">
                              {validationError.phone}
                            </p>
                          )}
                          <p className="text-muted-foreground mt-1 text-xs">
                            Enter 10-digit Indian phone number (e.g.,
                            9876543210)
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Action Buttons */}
                  <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                    <Button
                      variant="outline"
                      onClick={() => {
                        setIsEditOpen(false);
                        setValidationError({
                          name: null,
                          email: null,
                          phone: null,
                        });
                        setTouched({ name: false, email: false, phone: false });
                      }}
                    >
                      Cancel
                    </Button>
                    <Button
                      onClick={handleSaveProfile}
                      disabled={
                        saving ||
                        Object.values(validationError).some(
                          (err) => err !== null,
                        )
                      }
                    >
                      {saving ? "Saving..." : "Save changes"}
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* ── Change Password Dialog ── */}
      <Dialog open={isPassOpen} onOpenChange={setIsPassOpen}>
        <DialogContent className="max-w-md">
          <div className="mx-auto my-2 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
            <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>Change password</DialogTitle>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    setIsPassOpen(false);
                  }}
                />
              </DialogHeader>
              <div className="flex flex-grow flex-col p-4 pb-0 pl-2 pr-2">
                <div className="flex flex-1 flex-col pb-0">
                  <div className="max-h-[60vh] flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2">
                    <div className="space-y-1.5">
                      <label className="text-muted-foreground text-xs">
                        Current password
                      </label>
                      <div className="relative">
                        <input
                          type={showPass.current ? "text" : "password"}
                          className={`${inputClass} pr-10`}
                          placeholder="Enter current password"
                          value={passForm.currentPassword}
                          onChange={(e) =>
                            setPassForm((p) => ({
                              ...p,
                              currentPassword: e.target.value,
                            }))
                          }
                        />
                        <button
                          type="button"
                          onClick={() =>
                            setShowPass((p) => ({ ...p, current: !p.current }))
                          }
                          className="text-muted-foreground absolute right-3 top-1/2 -translate-y-1/2"
                        >
                          {showPass.current ? (
                            <EyeOff className="h-4 w-4" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </button>
                      </div>
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-muted-foreground text-xs">
                        New password
                      </label>
                      <div className="relative">
                        <input
                          type={showPass.new ? "text" : "password"}
                          className={`${inputClass} pr-10`}
                          placeholder="Min 6 characters"
                          value={passForm.newPassword}
                          onChange={(e) => {
                            setPassForm((p) => ({
                              ...p,
                              newPassword: e.target.value,
                            }));
                            checkStrength(e.target.value);
                          }}
                          onCopy={(e) => e.preventDefault()}
                          onPaste={(e) => e.preventDefault()}
                          onCut={(e) => e.preventDefault()}
                          onDrop={(e) => e.preventDefault()}
                        />
                        <button
                          type="button"
                          onClick={() =>
                            setShowPass((p) => ({ ...p, new: !p.new }))
                          }
                          className="text-muted-foreground absolute right-3 top-1/2 -translate-y-1/2"
                        >
                          {showPass.new ? (
                            <EyeOff className="h-4 w-4" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </button>
                      </div>
                      {passForm.newPassword && (
                        <div>
                          <div className="bg-border mt-1.5 h-1 overflow-hidden rounded-full">
                            <div
                              className="h-full rounded-full transition-all"
                              style={{
                                width: `${strength.score * 25}%`,
                                background: strength.color,
                              }}
                            />
                          </div>
                          <p
                            className="mt-1 text-xs"
                            style={{ color: strength.color }}
                          >
                            {strength.label}
                          </p>
                        </div>
                      )}
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-muted-foreground text-xs">
                        Confirm new password
                      </label>
                      <div className="relative">
                        <input
                          type={showPass.confirm ? "text" : "password"}
                          className={`${inputClass} pr-10`}
                          placeholder="Repeat new password"
                          value={passForm.confirmPassword}
                          onChange={(e) =>
                            setPassForm((p) => ({
                              ...p,
                              confirmPassword: e.target.value,
                            }))
                          }
                          onCopy={(e) => e.preventDefault()}
                          onPaste={(e) => e.preventDefault()}
                          onCut={(e) => e.preventDefault()}
                          onDrop={(e) => e.preventDefault()}
                        />
                        <button
                          type="button"
                          onClick={() =>
                            setShowPass((p) => ({ ...p, confirm: !p.confirm }))
                          }
                          className="text-muted-foreground absolute right-3 top-1/2 -translate-y-1/2"
                        >
                          {showPass.confirm ? (
                            <EyeOff className="h-4 w-4" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </button>
                      </div>
                      {passForm.confirmPassword &&
                        passForm.newPassword !== passForm.confirmPassword && (
                          <p className="text-destructive mt-1 text-xs">
                            Passwords do not match
                          </p>
                        )}
                    </div>
                  </div>
                  <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                    <Button
                      variant="outline"
                      onClick={() => {
                        setPassForm({
                          currentPassword: "",
                          newPassword: "",
                          confirmPassword: "",
                        });
                        setStrength({ score: 0, label: "", color: "" });
                        setIsPassOpen(false);
                      }}
                    >
                      Cancel
                    </Button>
                    <Button
                      onClick={handleUpdatePassword}
                      disabled={updatingPass}
                      className="text-white"
                    >
                      {updatingPass ? "Updating..." : "Update password"}
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
