"use client";
import { useState, useEffect } from "react";
import Image from "next/image";
import { HiArrowUpRight } from "react-icons/hi2";
import Link from "next/link";
import Faq from "@/src/components/web/Faq";
import { getTicketList, getCurrentCustomer } from "@/src/services/web/services";
import { Ticket } from "@/src/types/web/types";

const statusColors: Record<string, string> = {
  PENDING: "border-yellow-400 bg-yellow-50 text-yellow-600",
  IN_PROGRESS: "border-blue-400 bg-blue-50 text-blue-600",
  SOLVED: "border-green-400 bg-green-50 text-green-600",
  CLOSED: "border-gray-300 bg-gray-50 text-gray-500",
};

export default function TicketList() {
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [loading, setLoading] = useState(true);
  const [customerId, setCustomerId] = useState<number | null>(null);

  useEffect(() => {
    const fetchCustomer = async () => {
      try {
        const response = await getCurrentCustomer();
        const customer = response.data.user;
        
        setCustomerId(customer.id);
      } catch (error) {
        console.error("Error fetching customer:", error);
        setCustomerId(1);
      }
    };
    fetchCustomer();
  }, []);

  useEffect(() => {
    if (customerId) {
      loadTickets();
    }
  }, [customerId]);

  const loadTickets = async () => {
    try {
      setLoading(true);
      const response = await getTicketList({ customer_id: customerId ?? undefined, limit: 10 });
      setTickets(response.data.data);
    } catch (error) {
      console.error("Error loading tickets:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <section
        className="relative w-full bg-cover bg-center bg-no-repeat py-6 md:py-10 px-5 lg:px-20 rounded-lg overflow-hidden mt-5"
        style={{
          backgroundImage: "url('about/about-bg.png')",
        }}
      >
        <div className="absolute inset-0 bg-black/40"></div>

        <div className="relative z-10 max-w-7xl mx-auto">
          <nav className="inline-flex items-center gap-4 px-8 py-2 rounded-full bg-teal-transperent backdrop-blur-sm mb-6">
            <Link
              href="/"
              className="text-[15px] md:text-[17px]  text-white  font-medium cursor-pointer hover:underline"
            >
              Home
            </Link>

            <span className="text-white text-2xl leading-none">›</span>

            <span className=" text-[15px] md:text-[17px]  text-white  font-medium">
              Tickets List
            </span>
          </nav>

          <h1 className="text-[20px] lg:text-[35px] font-semibold text-white leading-tight md:leading-snug">
            <span className="inline-flex items-center gap-3 pr-[25px] relative">
              Let us know what's wrong & we'll take care of it.
              <Image
                src="/icons/top-arrow.svg"
                alt="Top Arrow"
                width={36}
                height={36}
                className="absolute right-[0px]  md:right-[-25px] lg:right-[-50px]  top-[-15px]"
              />
            </span>{" "}
            <br />
            Housing & Development.
          </h1>
        </div>
      </section>
      <section className="w-full py-10 px-0 lg:px-10 ">
        <div className="max-w-7xl mx-auto">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
            <div>
              <h2 className="text-[20px] md:text[35px] font-semibold text-gray-900">
                My Ticket Status
              </h2>
              <p className="text-gray-500 text-sm mt-1">
                Track & manage your housing application
              </p>
            </div>
            <Link href="/ticket/raise-a-ticket" className="cursor-pointer">
              <button className="flex items-center bg-[#1F8C8B] rounded-full pl-7 pr-2 py-2 text-white font-medium text-base hover:bg-[#187C7B] transition">
                <span className="mr-4 whitespace-nowrap">Raise New Ticket</span>
                <span className="flex items-center justify-center w-8 h-8 bg-white rounded-full">
                  <HiArrowUpRight className="w-6 h-6 text-black" />
                </span>
              </button>
            </Link>
          </div>

          <div className="space-y-6">
            {loading ? (
              <div className="text-center py-10 text-gray-500">Loading tickets...</div>
            ) : tickets.length === 0 ? (
              <div className="text-center py-10 text-gray-500">No tickets found</div>
            ) : (
              tickets.map((ticket) => (
                <div key={ticket.id} className="bg-white rounded-xl p-6 shadow-sm">
                  <div className="flex flex-col sm:flex-row sm:justify-between gap-2 mb-3">
                    <p className="text-sm font-medium text-gray-800">{ticket.ticket_no}</p>
                    <p className="text-xs text-gray-400">
                      {new Date(ticket.created_on).toLocaleString()}
                    </p>
                  </div>

                  <h3 className="text-gray-900 font-medium mb-2">{ticket.title}</h3>

                  <p className="text-sm text-gray-600 leading-relaxed line-clamp-2">
                    {ticket.description}
                  </p>

                  <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mt-5 pt-4 border-t">
                    <span
                      className={`px-3 py-1.5 rounded-md border text-xs font-medium w-fit ${
                        statusColors[ticket.status] || statusColors.PENDING
                      }`}
                    >
                      {ticket.status}
                    </span>
                    <Link
                      href={`/ticket/view-ticket?id=${ticket.id}`}
                      className="cursor-pointer"
                    >
                      <button className="text-teal-600 text-sm font-medium hover:underline w-fit">
                        Open Ticket
                      </button>
                    </Link>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </section>

      <Faq />
    </>
  );
}
