"use client";

import { useEffect, useState } from "react";
import {
  Upload,
  Plus,
  Settings,
  CheckCheck,
  Check,
  Clock,
  X,
} from "lucide-react";
import Image from "next/image";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { error, loading, success } from "@/config/swal";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useDropzone } from "react-dropzone";
import z from "zod";
import dynamic from "next/dynamic";
import { useParams, useRouter } from "next/navigation";
import Cookies from "js-cookie";
import { getProductDataById } from "@/service/product";
import {
  approveAgent,
  commentAgent,
  getAgentById,
  rejectAgent,
  updateAgent,
} from "@/service/agent";
import { Checkbox } from "@/components/ui/checkbox";
import { convertDateFormat } from "@/utils/global";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";

const ViewEditor = dynamic(
  () => {
    return import("@/components/editor/view-editor");
  },
  { ssr: false },
);
const CustomEditor = dynamic(
  () => {
    return import("@/components/editor/custom-editor");
  },
  { ssr: false },
);

interface FileWithPreview extends File {
  preview: string;
}

interface CategoryType {
  id: number;
  label: string;
  value: number;
}
const categorySchema = z.object({
  id: z.number(),
  label: z.string(),
  value: z.number(),
});

const AGENT_TYPES = [
  { key: "after-sales", label: "After Sales" },
  { key: "sales", label: "Sales" },
  { key: "spv", label: "SPV" },
  { key: "branch_manager", label: "Branch Manager" },
];

const createArticleSchema = z.object({
  title: z.string().min(2, {
    message: "Judul harus diisi",
  }),
  variant: z.string().min(2, {
    message: "variant diisi",
  }),
  price: z.string().min(2, {
    message: "Price harus diisi",
  }),
  category: z.array(categorySchema).nonempty({
    message: "Kategori harus memiliki setidaknya satu item",
  }),
  tags: z.array(z.string()).nonempty({
    message: "Minimal 1 tag",
  }), // Array berisi string
});

export default function DetailAgentForm(props: { isDetail: boolean }) {
  const { isDetail } = props;
  const params = useParams();
  const id = params?.id;
  const [data, setData] = useState<any>(null);
  const [openApproverHistory, setOpenApproverHistory] = useState(false);

  const router = useRouter();

  const [openCommentModal, setOpenCommentModal] = useState(false);
  const [commentValue, setCommentValue] = useState("");
  const handleSubmitComment = async () => {
    // await api.post("/banner/comment", {
    //   bannerId: viewBanner.id,
    //   comment: commentValue,
    // });

    setOpenCommentModal(false);
  };

  // 🔹 Ambil userlevelId dari cookies
  const [userRoleId, setUserRoleId] = useState<string | null>(null);

  const MySwal = withReactContent(Swal);

  // 🔹 Ambil userlevelId dari cookies
  useEffect(() => {
    const urie = Cookies.get("urie"); // contoh: "3"
    setUserRoleId(urie ?? null);
  }, []);

  useEffect(() => {
    fetchData();
  }, []);

  async function fetchData() {
    const res = await getAgentById(id);
    setData(res?.data?.data);
  }

  if (!data) return null;

  const handleOpenApproverHistory = () => {
    setOpenApproverHistory(true);
  };

  const handleCommentAgent = async (id: number) => {
    const { value: message } = await MySwal.fire({
      title: "Komen Agent",
      input: "textarea",
      inputLabel: "Komentar (opsional)",
      inputPlaceholder: "Masukkan komentar...",
      inputAttributes: {
        "aria-label": "Masukkan komentar",
      },
      showCancelButton: true,
      confirmButtonText: "Komentar",
      cancelButtonText: "Batal",
      confirmButtonColor: "#dc2626",
    });

    if (message === undefined) {
      return; // User cancelled
    }

    loading();
    const res = await commentAgent(id, message || undefined);

    if (res?.error) {
      error(res.message || "Gagal komentar agent");
      close();
      return;
    }

    close();
    success("Agent berhasil dikomentar");
    fetchData(); // refresh table
  };

  const handleRejectAgent = async (id: number) => {
    const MySwal = withReactContent(Swal);
    const { value: message } = await MySwal.fire({
      title: "Tolak Agent",
      input: "textarea",
      inputLabel: "Alasan penolakan (opsional)",
      inputPlaceholder: "Masukkan alasan penolakan...",
      inputAttributes: {
        "aria-label": "Masukkan alasan penolakan",
      },
      showCancelButton: true,
      confirmButtonText: "Tolak",
      cancelButtonText: "Batal",
      confirmButtonColor: "#dc2626",
    });

    if (message === undefined) {
      return; // User cancelled
    }

    loading();
    const res = await rejectAgent(id, message || undefined);

    if (res?.error) {
      error(res.message || "Gagal menolak agent");
      close();
      return;
    }

    close();
    success("Agent berhasil ditolak");
    fetchData(); // refresh table
  };

  const handleApproveAgent = async (id: number) => {
    loading();
    const res = await approveAgent(id);

    if (res?.error) {
      error(res.message || "Gagal menyetujui agent");
      close();
      return;
    }

    close();
    success("Agent berhasil disetujui");
    fetchData(); // refresh table
  };

  return (
    <>
      <Card className="w-full border-none shadow-md">
        <CardHeader>
          <CardTitle className="text-xl font-bold text-teal-900">
            Detail Agen
          </CardTitle>
        </CardHeader>

        <CardContent className="space-y-6">
          {/* FORM */}
          <div className="grid md:grid-cols-3 gap-4">
            <div>
              <Label className="mb-2">Nama Lengkap</Label>
              <Input value={data.name} readOnly />
            </div>

            <div>
              <Label className="mb-2">Jabatan</Label>
              <Input value={data.job_title} readOnly />
            </div>

            <div>
              <Label className="mb-2">No Telp</Label>
              <Input value={data.phone} readOnly />
            </div>
          </div>

          {/* JENIS AGEN */}
          <div>
            <Label className="mb-2 block">Jenis Agen</Label>
            <div className="flex gap-6">
              {AGENT_TYPES.map((item) => (
                <div key={item.key} className="flex items-center gap-2">
                  <Checkbox
                    checked={
                      Array.isArray(data.agent_type) &&
                      data.agent_type
                        .map((v: string) => v.toLowerCase())
                        .includes(item.label.toLowerCase())
                    }
                    disabled
                  />

                  <span>{item.label}</span>
                </div>
              ))}
            </div>
          </div>

          {/* FOTO PROFILE */}
          <div>
            <Label className="mb-2 block">Foto Profile</Label>
            <div className="w-24 h-24 rounded-lg overflow-hidden border">
              <img
                src={data?.profile_picture_url}
                alt="Profile"
                width={96}
                height={96}
                className="object-cover"
              />
            </div>
          </div>
          <div>
            <h4 className="text-sm font-semibold text-gray-700 mb-3">
              Status Timeline
            </h4>

            <div className="space-y-4">
              <div className="flex gap-3">
                <div className="w-6 h-6 rounded-full bg-green-100 flex items-center justify-center">
                  <Check className="w-4 h-4 text-green-600" />
                </div>
                <div>
                  <p className="font-medium text-gray-800">
                    Diupload oleh Operator
                  </p>
                  <p className="text-sm text-gray-500">
                    {convertDateFormat(data.created_at)} WIB
                  </p>
                </div>
              </div>
            </div>
            <div className="flex gap-3">
              <div
                className={`w-6 h-6 rounded-full flex items-center justify-center ${
                  data?.status_id === 1
                    ? "bg-yellow-100"
                    : data?.status_id === 2
                      ? "bg-green-100"
                      : "bg-red-100"
                }`}
              >
                {data?.status_id === 1 ? (
                  <Clock className="w-4 h-4 text-yellow-700" />
                ) : data?.status_id === 2 ? (
                  <Check className="w-4 h-4 text-green-600" />
                ) : (
                  <X className="w-4 h-4 text-red-700" />
                )}
              </div>

              <div>
                <p className="font-medium text-gray-800">
                  {data?.status_id === 1
                    ? "Menunggu disetujui oleh Approver"
                    : data?.status_id === 2
                      ? "Disetujui oleh Approver"
                      : "Ditolak oleh Approver"}
                </p>

                <p className="text-sm text-gray-500">
                  {convertDateFormat(data?.updated_at)} WIB
                </p>
              </div>
            </div>
          </div>
          <div className="border rounded-lg px-3 py-3">
            <p>Comment : </p>
            <div className="flex flex-row justify-between">
              <button
                onClick={handleOpenApproverHistory}
                className="text-sm text-blue-600 hover:underline mt-2"
              >
                View Approver History
              </button>
              <p>Jaecoo - Approver | 10/11/2026</p>
            </div>
          </div>
          {userRoleId !== "2" && data && (
            <div className="flex justify-between items-center gap-3 px-6 py-4 border-t bg-[#F2F7FA] mt-10">
              {data.status_id === 1 ? (
                <>
                  <Button
                    variant="secondary"
                    className="bg-blue-200 hover:bg-blue-400"
                    onClick={() => handleCommentAgent(data.id)}
                  >
                    Beri Tanggapan
                  </Button>

                  <Button
                    variant="destructive"
                    className="w-[180px]"
                    onClick={() => handleRejectAgent(data.id)}
                  >
                    Reject
                  </Button>

                  {userRoleId === "1" && (
                    <Button
                      className="bg-green-600 hover:bg-green-700 text-white w-[180px]"
                      onClick={() => handleApproveAgent(data.id)}
                    >
                      <CheckCheck className="w-4 h-4 mr-1" />
                      Approve
                    </Button>
                  )}
                </>
              ) : (
                <Button
                  variant="secondary"
                  className="mx-auto"
                  onClick={() => router.back()}
                >
                  Tutup
                </Button>
              )}
            </div>
          )}
          {/* <Button className=" bg-teal-800 hover:bg-teal-900 text-white py-3">
            Submit
          </Button> */}
        </CardContent>
      </Card>
      {openApproverHistory && (
        <div
          className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4"
          onClick={() => setOpenApproverHistory(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            {/* HEADER */}
            <div className="bg-gradient-to-br from-[#1F6779] to-[#0F6C75] text-white px-6 py-5 relative">
              <button
                onClick={() => setOpenApproverHistory(false)}
                className="absolute top-4 right-4 text-white/80 hover:text-white text-xl"
              >
                ✕
              </button>

              <h2 className="text-lg font-semibold">Approver History</h2>

              <div className="flex items-center gap-2 mt-3">
                <span className="bg-yellow-100 text-yellow-800 text-xs font-medium px-3 py-1 rounded-full">
                  Menunggu
                </span>
                <span className="bg-white text-[#0F6C75] text-xs font-medium px-3 py-1 rounded-full">
                  Banner
                </span>
                <span className="bg-white/20 text-white text-xs px-2 py-[2px] rounded-full">
                  1
                </span>
              </div>
            </div>

            {/* BODY */}
            <div className="p-6 grid grid-cols-[1fr_auto_1fr] gap-6 items-start">
              {/* LEFT TIMELINE */}
              <div className="relative space-y-6">
                {/* Upload */}
                <div className="flex flex-col items-center">
                  <span className="bg-[#C7DDE4] text-[#0F6C75] text-xs px-4 py-1 rounded-full">
                    Upload
                  </span>
                  <div className="w-px h-6 bg-gray-300" />
                </div>

                {/* Diterima */}
                <div className="relative bg-[#1F6779] text-white rounded-xl p-4">
                  <h4 className="font-semibold text-sm mb-2">Diterima</h4>
                  <span className="inline-block bg-[#E3EFF4] text-[#0F6C75] text-xs px-3 py-1 rounded-full">
                    Direview oleh: approver-jaecoo1
                  </span>
                </div>

                <div className="w-px h-6 bg-gray-300 mx-auto" />

                {/* Pending */}
                <div className="relative bg-[#B36A00] text-white rounded-xl p-4">
                  <h4 className="font-semibold text-sm mb-2">Pending</h4>
                  <span className="inline-block bg-[#FFF6CC] text-[#7A4A00] text-xs px-3 py-1 rounded-full">
                    Direview oleh: approver-jaecoo1
                  </span>
                </div>
              </div>

              {/* ARROW */}
              <div className="flex flex-col gap-20 text-gray-500 font-bold">
                <span>&gt;</span>
                <span>&gt;</span>
              </div>

              {/* RIGHT NOTES */}
              <div className="space-y-14">
                <div>
                  <div className="bg-[#C7DDE4] text-sm px-4 py-2 rounded-lg">
                    Catatan:
                  </div>
                </div>

                <div>
                  <div className="bg-[#FFF9C4] text-sm px-4 py-2 rounded-lg">
                    Catatan:
                  </div>
                </div>
              </div>
            </div>

            {/* FOOTER */}
            <div className="border-t bg-[#F2F7FA] text-center py-3">
              <button
                onClick={() => setOpenApproverHistory(false)}
                className="text-[#0F6C75] font-medium hover:underline"
              >
                Tutup
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
