"use client";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { control } from "leaflet";
import React, { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import { getBlog, postBlog } from "@/service/blog/blog";
import { id } from "date-fns/locale";
import router from "next/router";
import { getInfoProfile, saveUser } from "@/service/auth";
import withReactContent from "sweetalert2-react-content";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Link } from "@/components/navigation";

const profileSchema = z.object({
  username: z.string().min(1, { message: "Judul diperlukan" }),
  fullname: z.string().min(1, { message: "Judul diperlukan" }),
  memberIdentity: z.string().min(1, { message: "Judul diperlukan" }),
  email: z.string().min(1, { message: "Judul diperlukan" }),
  address: z
    .string()
    .min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter." }),
  phoneNumber: z.string().min(1, { message: "Kategori diperlukan" }),
});

type Detail = {
  id: number;
  userId: any;
  firstName: string;
  username: string;
  fullname: string;
  memberIdentity: any;
  email: string;
  address: string;
  phoneNumber: any;
  message: string;
};

const UbahProfile: React.FC = () => {
  const MySwal = withReactContent(Swal);
  const [detail, setDetail] = useState<Detail>();
  const [refresh, setRefresh] = useState(false);

  type ProfileSchema = z.infer<typeof profileSchema>;
  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<ProfileSchema>({
    resolver: zodResolver(profileSchema),
  });

  useEffect(() => {
    async function initState() {
      const response = await getInfoProfile();
      const details = response?.data?.data;

      setDetail(details);
      console.log("data", details);
    }

    initState();
  }, []);

  const save = async (data: ProfileSchema) => {
    const requestData = {
      ...data,
      // userId: detail?.userKeycloakId,
      firstName: detail?.fullname,
      username: detail?.username,
      memberIdentity: detail?.memberIdentity,
      email: detail?.email,
      address: detail?.address,
      phoneNumber: detail?.phoneNumber,
      // message: data.title,
    };

    const response = await saveUser(requestData);
    console.log("Form Data Submitted:", requestData);
    console.log("response", response);

    MySwal.fire({
      title: "Sukses",
      text: "Data berhasil disimpan.",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then(() => {
      router.push("/en/auth");
    });
  };

  const onSubmit = (data: ProfileSchema) => {
    MySwal.fire({
      title: "Simpan Data",
      text: "Apakah Anda yakin ingin menyimpan data ini?",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Simpan",
    }).then((result) => {
      if (result.isConfirmed) {
        save(data);
      }
    });
  };
  return (
    <div className="px-4 lg:px-14 py-8">
      <div className="text-center mb-8">
        <div className="w-20 h-20 mx-auto rounded-full bg-red-700 flex items-center justify-center">
          <span className="text-white text-3xl font-bold">👤</span>
        </div>
        <h1 className="text-2xl font-bold mt-4">Ubah Profile</h1>
      </div>
      <div className="flex justify-center gap-4 mb-8">
        <Link href={"/profile"}>
          <button className="bg-red-700 text-white px-4 py-2 rounded">
            User Profile
          </button>
        </Link>
        <Link href={"/profile/change-profile"}>
          <button className="border border-red-700 text-red-700 px-4 py-2 rounded">
            Ubah Foto
          </button>
        </Link>
        <Link href={"/profile/change-password"}>
          <button className="border border-red-700 text-red-700 px-4 py-2 rounded">
            Ubah Password
          </button>
        </Link>
      </div>

      <div className="max-w-3xl mx-auto bg-white shadow-sm p-4 rounded">
        <p className="mb-6 text-gray-600">
          Silahkan ubah data pribadi Anda pada form berikut.
        </p>
        <form onSubmit={handleSubmit(onSubmit)}>
          {detail !== undefined ? (
            <div>
              <div className="mb-4">
                <Label>
                  Username<span className="text-red-500">*</span>
                </Label>
                <Controller
                  control={control}
                  name="username"
                  render={({ field }) => (
                    <Input
                      size="md"
                      type="text"
                      defaultValue={detail?.username}
                      onChange={field.onChange}
                      placeholder="Enter Title"
                    />
                  )}
                />
                {errors.username?.message && (
                  <p className="text-red-400 text-sm">
                    {errors.username.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <Label>
                  Nama Lengkap<span className="text-red-500">*</span>
                </Label>
                <Controller
                  control={control}
                  name="fullname"
                  render={({ field }) => (
                    <Input
                      size="md"
                      type="text"
                      defaultValue={detail?.fullname}
                      onChange={field.onChange}
                      placeholder="Enter Title"
                    />
                  )}
                />
                {errors.fullname?.message && (
                  <p className="text-red-400 text-sm">
                    {errors.fullname.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <Label>
                  Nomor Identitas<span className="text-red-500">*</span>
                </Label>
                <Controller
                  control={control}
                  name="memberIdentity"
                  render={({ field }) => (
                    <Input
                      size="md"
                      type="text"
                      defaultValue={detail?.memberIdentity}
                      onChange={field.onChange}
                      placeholder="Enter Title"
                    />
                  )}
                />
                {errors.memberIdentity?.message && (
                  <p className="text-red-400 text-sm">
                    {errors.memberIdentity.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <Label>
                  Email<span className="text-red-500">*</span>
                </Label>
                <Controller
                  control={control}
                  name="email"
                  render={({ field }) => (
                    <Input
                      size="md"
                      type="text"
                      defaultValue={detail?.email}
                      onChange={field.onChange}
                      placeholder="Enter Title"
                    />
                  )}
                />
                {errors.email?.message && (
                  <p className="text-red-400 text-sm">{errors.email.message}</p>
                )}
              </div>
              <div className="mb-4">
                <Label>
                  Nomor HP<span className="text-red-500">*</span>
                </Label>
                <Controller
                  control={control}
                  name="phoneNumber"
                  render={({ field }) => (
                    <Input
                      size="md"
                      type="number"
                      defaultValue={detail?.phoneNumber}
                      onChange={field.onChange}
                      placeholder="Enter Title"
                    />
                  )}
                />
                {errors.phoneNumber?.message && (
                  <p className="text-red-400 text-sm">
                    {errors.phoneNumber.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <Label>
                  Alamat<span className="text-red-500">*</span>
                </Label>
                <Controller
                  control={control}
                  name="address"
                  render={({ field }) => (
                    <Textarea
                      defaultValue={detail?.address}
                      onChange={field.onChange}
                      placeholder="Enter Title"
                    />
                  )}
                />
                {errors.address?.message && (
                  <p className="text-red-400 text-sm">
                    {errors.address.message}
                  </p>
                )}
              </div>
              <div className="text-right">
                <div className="mt-4">
                  <button
                    type="submit"
                    className="bg-red-700 text-white px-6 py-2 rounded hover:bg-red-800 focus:outline-none focus:ring focus:ring-red-300"
                  >
                    Simpan
                  </button>
                </div>
              </div>
            </div>
          ) : (
            ""
          )}
        </form>
      </div>
    </div>
  );
};

export default UbahProfile;
