"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";
import { X } from "lucide-react";

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 [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);

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

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

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getAgentById(id);

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

        setAgentData(res.data);

        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.data.profile_picture_path || null);
      } catch (err) {
        console.error("ERROR FETCH DATA AGENT:", err);
      } finally {
        setLoading(false);
      }
    }

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

  const handleFileChange = (e: any) => {
    const selected = e.target.files[0];
    if (selected) {
      setFile(selected);
      setPreview(URL.createObjectURL(selected));
    }
  };

  const handleRemoveFile = () => {
    setFile(null);
    setPreview(null);
  };

  const onSubmit = async (data: AgentFormValues) => {
    try {
      const formData = new FormData();

      formData.append("name", data.fullName);
      formData.append("job_title", data.position);
      formData.append("phone", data.phone);

      data.roles.forEach((role) => {
        formData.append("agent_type", role);
      });

      if (file) {
        formData.append("file", file);
      }

      await updateAgent(id, formData);

      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">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
            <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">
              {preview && (
                <div className="mt-3 relative w-28 h-28 rounded-md overflow-hidden border">
                  <img
                    src={preview}
                    alt="Preview"
                    className="w-full h-full object-cover"
                  />
                  <button
                    type="button"
                    onClick={handleRemoveFile}
                    className="absolute top-1 right-1 bg-red-600 text-white p-1 rounded-full"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              )}

              <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={handleFileChange}
              />
            </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>
  );
}
