"use client";

import { 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 { createAgent } from "@/service/agent";
import { useRouter } from "next/navigation";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";

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

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

export default function AddAgentForm() {
  const [previewImg, setPreviewImg] = useState<string | null>(null);
  const router = useRouter();

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

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

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

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

      const res = await createAgent(payload);
      console.log("SUCCESS:", res);
    } catch (err) {
      console.error("ERROR CREATE AGENT:", err);
    }
    successSubmit("/admin/agent");
  };

  function successSubmit(redirect: any) {
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        router.push(redirect);
      }
    });
  }

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

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          {/* GRID INPUT */}
          <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 <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input placeholder="Masukkan Nama" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Jabatan */}
            <FormField
              control={form.control}
              name="position"
              rules={{ required: true }}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    Jabatan <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Contoh: Spv atau Branch Manager"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* No Telp */}
            <FormField
              control={form.control}
              name="phone"
              rules={{ required: true }}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    No Telp <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input placeholder="Contoh: 021-123-xxx" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          {/* CHECKBOX ROLE */}
          <div>
            <FormLabel>
              Pilih Jenis Agen <span className="text-red-500">*</span>
            </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
                        key={role}
                        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>

          {/* UPLOAD FOTO */}
          <div className="space-y-3">
            <FormLabel>
              Upload Foto Profile <span className="text-red-500">*</span>
            </FormLabel>

            <div className="relative border-2 border-dashed rounded-xl bg-slate-50 dark:bg-neutral-800 p-6 flex flex-col items-center cursor-pointer">
              {previewImg ? (
                <img
                  src={previewImg}
                  className="w-32 h-32 rounded-full object-cover mb-4"
                />
              ) : (
                <div className="flex flex-col items-center">
                  <div className="bg-teal-200 p-4 rounded-full mb-3">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                      strokeWidth={1.8}
                      stroke="currentColor"
                      className="w-8 h-8 text-teal-700"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        d="M12 16.5v-9m0 0L9 10m3-2.5l3 2.5m1.5 9H6a1.5 1.5 0 01-1.5-1.5v-12A1.5 1.5 0 016 3h12a1.5 1.5 0 011.5 1.5v12a1.5 1.5 0 01-1.5 1.5z"
                      />
                    </svg>
                  </div>
                  <p className="text-gray-600 dark:text-gray-300">
                    Klik untuk upload atau drag & drop
                  </p>
                  <p className="text-xs text-gray-500 mt-1">
                    PNG, JPG (max 2 MB)
                  </p>
                </div>
              )}

              <input
                type="file"
                className="absolute inset-0 opacity-0 cursor-pointer"
                accept="image/*"
                onChange={(e) => handleImageChange(e.target.files?.[0])}
              />
            </div>
          </div>

          {/* BUTTON */}
          <Button type="submit" className="bg-teal-700 hover:bg-teal-800">
            Tambahkan Agen
          </Button>
        </form>
      </Form>
    </div>
  );
}
