"use client";

import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { getAgentById, updateAgent } from "@/service/agent";
import { useRouter } from "next/navigation";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";

type AgentFormValues = {
  fullName: string;
  position: string;
  phone: string;
  roles: string[];
  profileImage: File | null;
};

const agentTypes = ["After Sales", "Sales", "Spv", "Branch Manager"];

export default function UpdateAgentForm({ id }: { id: number }) {
  const [loading, setLoading] = useState(true);
  const [previewImg, setPreviewImg] = useState<string | null>(null);
  const [agentData, setAgentData] = useState<any>(null);

  const router = useRouter();
  const MySwal = withReactContent(Swal);

  const form = useForm<AgentFormValues>({
    defaultValues: {
      fullName: "",
      position: "",
      phone: "",
      roles: [],
      profileImage: null,
    },
  });

  // ================================
  // 🔥 FETCH API & SET DEFAULT VALUES
  // ================================
  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getAgentById(id);

        if (!res || !res.data) {
          console.error("DATA AGENT TIDAK DITEMUKAN");
          return;
        }

        setAgentData(res.data);

        // set form default values
        form.reset({
          fullName: res?.data?.data?.name,
          position: res?.data?.data?.job_title,
          phone: res?.data?.data?.phone,
          roles: res?.data?.data?.agent_type || [],
          profileImage: null,
        });

        console.log("name", res?.data?.data?.name);
        setPreviewImg(res.data.profile_picture_path || null);
      } catch (err) {
        console.error("ERROR FETCH DATA AGENT:", err);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, [id, form]);

  const handleImageChange = (file?: File) => {
    if (!file) return;
    form.setValue("profileImage", file);

    const preview = URL.createObjectURL(file);
    setPreviewImg(preview);
  };

  const onSubmit = async (data: AgentFormValues) => {
    const payload = {
      name: data.fullName,
      job_title: data.position,
      phone: data.phone,
      agent_type: data.roles,
      profile_picture_path: data.profileImage
        ? data.profileImage.name
        : agentData.profile_picture_path,
    };

    try {
      await updateAgent(id, payload);
      successSubmit("/admin/agent");
    } catch (err) {
      console.error("ERROR UPDATE AGENT:", err);
    }
  };

  function successSubmit(redirect: string) {
    MySwal.fire({
      title: "Data Berhasil Diupdate",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((res) => {
      if (res.isConfirmed) router.push(redirect);
    });
  }

  if (loading) {
    return <div className="p-6 text-gray-600">Loading data...</div>;
  }

  return (
    <div className="bg-white dark:bg-neutral-900 p-6 rounded-lg shadow-sm">
      <h2 className="text-2xl font-bold text-teal-800 mb-6">Edit Agen</h2>

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          {/* INPUT GRID */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
            {/* Nama */}
            <FormField
              control={form.control}
              name="fullName"
              rules={{ required: true }}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Nama Lengkap *</FormLabel>
                  <FormControl>
                    <Input placeholder="Masukkan Nama" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />

            {/* Jabatan */}
            <FormField
              control={form.control}
              name="position"
              rules={{ required: true }}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Jabatan *</FormLabel>
                  <FormControl>
                    <Input placeholder="Contoh: Branch Manager" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />

            {/* Telepon */}
            <FormField
              control={form.control}
              name="phone"
              rules={{ required: true }}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>No Telp *</FormLabel>
                  <FormControl>
                    <Input placeholder="Contoh: 0812xxxx" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />
          </div>

          {/* ROLES */}
          <div>
            <FormLabel>Pilih Jenis Agen *</FormLabel>

            <div className="flex flex-wrap gap-6 mt-3">
              {agentTypes.map((role) => (
                <FormField
                  key={role}
                  control={form.control}
                  name="roles"
                  render={({ field }) => {
                    const selected = field.value || [];
                    return (
                      <FormItem className="flex flex-row items-center space-x-2">
                        <FormControl>
                          <Checkbox
                            checked={selected.includes(role)}
                            onCheckedChange={(checked) => {
                              const updated = checked
                                ? [...selected, role]
                                : selected.filter((i) => i !== role);
                              field.onChange(updated);
                            }}
                          />
                        </FormControl>
                        <FormLabel className="font-normal">{role}</FormLabel>
                      </FormItem>
                    );
                  }}
                />
              ))}
            </div>
          </div>

          {/* FOTO */}
          <div className="space-y-3">
            <FormLabel>Foto Agen</FormLabel>

            <div className="flex items-center gap-5">
              {previewImg && (
                <img
                  src={previewImg}
                  className="w-24 h-24 rounded-lg object-cover shadow"
                />
              )}

              <Button
                type="button"
                className="bg-teal-700 hover:bg-teal-800 text-white"
                onClick={() => document.getElementById("upload-photo")?.click()}
              >
                Upload Baru
              </Button>

              <input
                id="upload-photo"
                type="file"
                className="hidden"
                accept="image/*"
                onChange={(e) => handleImageChange(e.target.files?.[0])}
              />
            </div>
          </div>

          {/* BUTTON */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-5">
            <Button
              type="button"
              className="bg-gray-300 text-gray-700 hover:bg-gray-400"
              onClick={() => router.back()}
            >
              Batal
            </Button>

            <div className="md:col-span-2">
              <Button
                type="submit"
                className="w-full bg-teal-700 hover:bg-teal-800 text-white py-3"
              >
                Simpan Perubahan
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </div>
  );
}
