// "use client";
// import { Button } from "@/components/ui/button";
// import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
// import Image from "next/image";
// import React from "react";
// import { SignUp } from "./SignUp";
// import {
//   Card,
//   CardContent,
//   CardDescription,
//   CardFooter,
//   CardHeader,
//   CardTitle,
// } from "@/components/ui/card";
// import { Label } from "@/components/ui/label";
// import { Input } from "@/components/ui/input";
// import Link from "next/link";

// const EditProfileModal = ({ open, setOpen }) => {
//   return (
//     <div>
//       <Dialog open={open} onOpenChange={setOpen}>
       
//         <DialogContent className="sm:max-w-[625px] h-[80vh] rounded-2xl overflow-auto">
//         <div className=" h-full">
//           <DialogHeader>
//             <DialogTitle>Edit profile</DialogTitle>
         
//           </DialogHeader>
//           <div className="grid gap-4">
            
//             <div className="grid gap-3 mt-5">
//               <Label htmlFor="name-1">Name</Label>
//               <Input id="name-1" name="name"  />
//             </div>
//             <div className="grid gap-3">
//               <Label htmlFor="email">Email</Label>
//               <Input id="email" name="email"  />
//             </div>
//             <div className="grid gap-3">
//               <Label htmlFor="password">Password</Label>
//               <Input id="password" name="password"  />
//             </div>
           
//           </div>
//           <DialogFooter className='mt-3'>
//             <DialogClose asChild>
//               <Button variant="outline">Cancel</Button>
//             </DialogClose>
//             <Button type="submit">Save changes</Button>
//           </DialogFooter>
//         </div>
//         </DialogContent>
//       </Dialog>
      
//     </div>
//   );
// };

// export default EditProfileModal;
'use client';
import React, { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogClose,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { baseUrl } from '@/lib/config';

const EditProfileModal = ({ open, setOpen, emailP,nameP }) => {
  // Local state for profile form
  console.log(emailP,nameP)
  const [name, setName] = useState(nameP);
  const [email, setEmail] = useState(emailP);
useEffect(() => {
 setName(nameP)
setEmail(emailP)
}, [nameP,emailP])

  // Local state for change password modal
  const [changePassOpen, setChangePassOpen] = useState(false);
  const [currentPass, setCurrentPass] = useState('');
  const [newPass, setNewPass] = useState('');
  const [confirmPass, setConfirmPass] = useState('');
  const [passError, setPassError] = useState('');
  const [passErrorAPI, setPassErrorAPI] = useState('');

  // Profile submit handler
  // const handleProfileSubmit = (e) => {
  //   e.preventDefault();
  //   // TODO: call API to update profile
  //   // Example: await updateProfile({ name, email })
  //   // For now just close
  //   setOpen(false);
  // };

const handleProfileSubmit = async (e) => {
  e.preventDefault();

  try {
    // Get token from localStorage
    const token = localStorage.getItem("sadu_auth_token"); // change key if needed
    if (!token) {
      console.error("No token found in localStorage");
      return;
    }

    // Prepare payload
    const payload = {
      name: name,
      email: email,
    };

    // Call API
    const res = await fetch(`${baseUrl}/api/update-user`, {
      method: "POST", // or "PUT" if backend expects PUT
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(payload),
    });

    const data = await res.json();

    if (!res.ok) {
      console.error("Failed to update:", data);
      return;
    }
localStorage.setItem('name',data?.user?.name)
localStorage.setItem('email',data?.user?.email)
    console.log("Profile updated successfully:", data);
    setOpen(false); // close modal on success
  } catch (error) {
    console.error("Error updating profile:", error);
  }
};


  // Password submit handler
  const handlePasswordSubmit = async (e) => {
    e.preventDefault();
    setPassError('');
    setPassErrorAPI('');
    if (!currentPass) {
      setPassError('Please enter your current password.');
      return;
    }
    if (newPass.length < 6) {
      setPassError('New password must be at least 6 characters.');
      return;
    }
    if (newPass !== confirmPass) {
      setPassError('New password and confirm password do not match.');
      return;
    }
try {
    // Get token from localStorage
    const token = localStorage.getItem("sadu_auth_token"); // change key if needed
    if (!token) {
      console.error("No token found in localStorage");
      return;
    }

    // Prepare payload
    const payload = {
      current_password: currentPass,
      new_password: newPass,
      new_password_confirmation: confirmPass,
    };

    // Call API
    const res = await fetch(`${baseUrl}/api/change-password`, {
      method: "POST", // or "PUT" if backend expects PUT
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(payload),
    });

    const data = await res.json();
    setPassErrorAPI(data?.message)

    if (!res.ok) {
      console.error("Failed to update:", data);
      return;
    }
    console.log("Password updated successfully:", data);
  } catch (error) {
    console.error("Error updating Password:", error);
    // setPassErrorAPI(error?.message)
  }
    // TODO: call change password API: changePassword({ currentPass, newPass })
    // On success:
    setChangePassOpen(false);
    setCurrentPass('');
    setNewPass('');
    setConfirmPass('');
    // Optionally show toast / message
  };

  return (
    <>
      {/* Edit Profile Modal (controlled by parent) */}
      <Dialog open={open} onOpenChange={setOpen}>
        <form onSubmit={handleProfileSubmit}>
          <DialogContent className="sm:max-w-[625px] max-h-[90vh] overflow-auto rounded-2xl">
            <div className="py-5">
              <DialogHeader>
                <DialogTitle>Edit profile</DialogTitle>
              </DialogHeader>

              <div className="grid gap-4 mt-4">
                <div className="grid gap-2">
                  <Label htmlFor="name-1">Name</Label>
                  <Input
                   className=' h-11 lg:h-[60px] text-[14px] sm:text-[16px]'
                    id="name-1"
                    name="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="Your name"
                  />
                </div>

                <div className="grid gap-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                   className=' h-11 lg:h-[60px] text-[14px] sm:text-[16px]'
                    id="email"
                    name="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="you@example.com"
                    type="email"
                  />
                </div>

                {/* REMOVE password field and add Change Password button */}
                <div className="mt-4">
                  <Label>Security</Label>
                  <div className="sm:flex items-center gap-3 mt-2">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setChangePassOpen(true)}
                    >
                      Change Password
                    </Button>
                    <p className="text-sm pt-2 ps-2 sm:p-0 text-muted-foreground">
                      Click to update your password
                    </p>
                  </div>
                </div>
              </div>

              <DialogFooter className="mt-6 flex justify-end gap-3">
                <DialogClose asChild>
                  <Button variant="outline" type="button" onClick={() => setOpen(false)}>
                    Cancel
                  </Button>
                </DialogClose>
                <Button type="submit" onClick={handleProfileSubmit}>Save changes</Button>
              </DialogFooter>
            </div>
          </DialogContent>
        </form>
      </Dialog>

      {/* Change Password Modal (controlled locally) */}
      <Dialog open={changePassOpen} onOpenChange={setChangePassOpen}>
        <form onSubmit={handlePasswordSubmit}>
          <DialogContent className="sm:max-w-[520px] max-h-[90vh] overflow-auto rounded-2xl">
            <div className="py-5">
              <DialogHeader>
                <DialogTitle>Change Password</DialogTitle>
              </DialogHeader>

              <div className="grid gap-3 mt-4">
                <div className="grid gap-2">
                  <Label htmlFor="current-pass">Current password</Label>
                  <Input
                   className=' h-11 lg:h-[60px] text-[14px] sm:text-[16px]'
                    id="current-pass"
                    name="currentPass"
                    type="password"
                    value={currentPass}
                    onChange={(e) => setCurrentPass(e.target.value)}
                    placeholder="Current password"
                  />
                </div>

                <div className="grid gap-2">
                  <Label htmlFor="new-pass">New password</Label>
                  <Input
                   className=' h-11 lg:h-[60px] text-[14px] sm:text-[16px]'
                    id="new-pass"
                    name="newPass"
                    type="password"
                    value={newPass}
                    onChange={(e) => setNewPass(e.target.value)}
                    placeholder="New password"
                  />
                </div>

                <div className="grid gap-2">
                  <Label htmlFor="confirm-pass">Confirm new password</Label>
                  <Input
                   className=' h-11 lg:h-[60px] text-[14px] sm:text-[16px]'
                    id="confirm-pass"
                    name="confirmPass"
                    type="password"
                    value={confirmPass}
                    onChange={(e) => setConfirmPass(e.target.value)}
                    placeholder="Confirm new password"
                  />
                </div>

                {passError && (
                  <p className="text-sm text-red-600 mt-2">{passError}</p>
                )}
                {passErrorAPI && (
                  <p className="text-sm text-red-600 mt-2">{passErrorAPI}</p>
                )}
              </div>

              <DialogFooter className="mt-6 flex justify-end gap-3">
                <DialogClose asChild>
                  <Button
                    variant="outline"
                    type="button"
                    onClick={() => {
                      setChangePassOpen(false);
                      setPassError('');
                    }}
                  >
                    Cancel
                  </Button>
                </DialogClose>
                <Button type="button" onClick={handlePasswordSubmit}>Update password</Button>
              </DialogFooter>
            </div>
          </DialogContent>
        </form>
      </Dialog>
    </>
  );
};

export default EditProfileModal;
