"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";

interface AdminProfile {
  _id?: string;
  name: string;
  email: string;
  phone: string;
  username: string;
  // bio: 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 [profile, setProfile] = useState<AdminProfile>({
    name: "Admin User",
    email: "admin@dulhesahab.com",
    phone: "+91 9000000000",
    username: "Admin User",
    // bio: "Managing Dulhe Sahab admin panel",
    avatar: "",
    passwordChangedAt: null
  });

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

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

  const handleSaveProfile = async () => {    
    const hasError = Object.values(validationError).some((err) => err);
    if(hasError) return
    setSaving(true);
    try {
      const formData = new FormData();
      Object.entries(editForm).forEach(([k, v]) => {
        if (k !== "avatar") {
          formData.append(k, v || "");
        }
      });

      if (avatarFile) {
        // New uploaded file
        formData.append("avatar", avatarFile);
      } else {
        // Keep existing avatar
        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();
        setIsEditOpen(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 checkValidation = (key: string, value: any) => {
    let error = null;

    switch (key) {
      case 'phone': {
        // Indian phone number: starts with 6-9 and has 10 digits
        const phoneRegex = /^[6-9]\d{9}$/;
        if (!phoneRegex.test(value)) {
          error = 'Invalid Indian phone number';
        }
        break;
      }

      case 'email': {
        // Standard email regex
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(value)) {
          error = 'Invalid email address';
        }
        break;
      }

      default:
        error = null;
    }

    setValidationError((prev: any) => ({
      ...prev,
      [key]: error,
    }));

    return error;
  };

  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";

  return (
    <div className="space-y-4">

      {/* Page header */}
      <div>
        {/* <p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">Settings</p> */}
        <h1 className="text-2xl font-semibold">My profile</h1>
      </div>

      {/* Profile card — read only */}
      {dataLoading ? <div className="flex justify-center items-center h-64">Loading...</div>
      : (<div className="rounded-xl border bg-card">

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

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

          {/* {profile.bio && (
            <div className="col-span-2">
              <p className="text-xs text-muted-foreground mb-1">Bio</p>
              <p className="text-sm">{profile.bio}</p>
            </div>
          )} */}
        </div>

        {/* Password row */}
        <div className="px-6 py-3 border-t flex items-center justify-between">
          <div>
            <p className="text-sm font-medium">Password</p>
            <p className="text-xs text-muted-foreground mt-0.5">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="w-3.5 h-3.5" />
            Change password
          </Button>
        </div>
      </div>
      )}

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

                      <div className="grid grid-cols-2 gap-4">
                        <div className="">
                          <label className="text-xs text-muted-foreground">Name</label>
                          <input
                            className={inputClass}
                            value={editForm.name}
                            onChange={(e) => setEditForm((p) => ({ ...p, name: e.target.value }))}
                          />
                        </div>
                        {/* <div className="space-y-1.5">
                          <label className="text-xs text-muted-foreground">Username</label>
                          <input
                            className={inputClass}
                            value={editForm.username}
                            onChange={(e) => setEditForm((p) => ({ ...p, username: e.target.value }))}
                          />
                      </div> */}

                        <div className="">
                            <label className="text-xs text-muted-foreground">Email address</label>
                            <input
                              type="email"
                              className={inputClass}
                              value={editForm.email}
                              onChange={(e) => {
                                setEditForm((p) => ({ ...p, email: e.target.value }))
                                checkValidation('email', e.target.value)
                              }}
                            />
                            {validationError?.email &&
                            <span className='text-sm text-red-400'>{validationError.email}</span>}
                        </div>
                      </div>

                      <div className="grid grid-cols-1 gap-4">                        
                        <div className="mb-4">
                          <label className="text-xs text-muted-foreground">Phone number</label>
                          <input
                            type="tel"
                            className={inputClass}
                            value={editForm.phone}
                            onChange={(e) => {
                              setEditForm((p) => ({ ...p, phone: e.target.value }))
                              checkValidation('phone', e.target.value)
                            }}
                          />
                          {validationError?.phone && 
                            <span className='text-sm text-red-400'>{validationError.phone}</span>}
                        </div>
                      </div>            

                      {/* <div className="space-y-1.5">
                        <label className="text-xs text-muted-foreground">Bio</label>
                        <textarea
                          rows={2}
                          className={`${inputClass} resize-none`}
                          value={editForm.bio}
                          onChange={(e) => setEditForm((p) => ({ ...p, bio: e.target.value }))}
                        />
                      </div> */}
                    </div>

                  </div>
                  <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                    <Button variant="outline" onClick={() => setIsEditOpen(false)}>Cancel</Button>
                    <Button onClick={handleSaveProfile} disabled={saving}>
                      {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="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-2 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>Change password</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsPassOpen(false);
                  }}
                />
              </DialogHeader>
              <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-grow">
                <div className="flex flex-col flex-1 pb-0">
                  <div className="max-h-[60vh] flex-1 pl-2 overflow-y-auto space-y-4 pb-4 pr-2">
                    <div className="space-y-1.5">
                      <label className="text-xs text-muted-foreground">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="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground"
                        >
                          {showPass.current ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </button>
                      </div>
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-xs text-muted-foreground">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="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground"
                        >
                          {showPass.new ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </button>
                      </div>
                      {passForm.newPassword && (
                        <div>
                          <div className="h-1 rounded-full bg-border overflow-hidden mt-1.5">
                            <div
                              className="h-full rounded-full transition-all"
                              style={{ width: `${strength.score * 25}%`, background: strength.color }}
                            />
                          </div>
                          <p className="text-xs mt-1" style={{ color: strength.color }}>{strength.label}</p>
                        </div>
                      )}
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-xs text-muted-foreground">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="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground"
                        >
                          {showPass.confirm ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </button>
                      </div>
                      {passForm.confirmPassword && passForm.newPassword !== passForm.confirmPassword && (
                        <p className="text-xs text-destructive mt-1">Passwords do not match</p>
                      )}
                    </div>

                  </div>
                  <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                    <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>
  );
}