"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";
import { Label } from "@/components/ui/label";
import { UploadCloud } from "lucide-react";

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

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

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

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

  const handleFileChange = (e: any) => {
    const selected = e.target.files[0];
    if (selected) setFile(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.job_title);
      formData.append("phone", data.phone);

      formData.append("agent_type", JSON.stringify(data.agent_type));

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

      const res = await createAgent(formData);
      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">
          <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 <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input placeholder="Masukkan Nama" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="job_title"
              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>
              )}
            />

            <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>

          <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="agent_type"
                  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>

          <div>
            <Label className="text-gray-700">
              Upload Foto Profil <span className="text-red-500">*</span>
            </Label>
            <label
              htmlFor="uploadFile"
              className="mt-1 border-2 border-dashed border-gray-300 rounded-xl p-6 flex flex-col items-center justify-center text-gray-500 cursor-pointer hover:border-[#1F6779]/50 transition"
            >
              <UploadCloud className="w-10 h-10 text-[#1F6779] mb-2" />
              <p className="text-sm font-medium">
                Klik untuk upload atau drag & drop
              </p>
              <p className="text-xs text-gray-400 mt-1">PNG, JPG (max 2 MB)</p>
              <input
                id="uploadFile"
                type="file"
                accept="image/png, image/jpeg"
                className="hidden"
                onChange={handleFileChange}
              />
              {file && (
                <p className="mt-2 text-xs text-[#1F6779] font-medium">
                  {file.name}
                </p>
              )}
            </label>
          </div>

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