"use client";

import { useState, useEffect } from "react";
import dynamic from "next/dynamic";
import { useTranslations } from "next-intl";
import { customInstance } from "@/config/axios";
import deleteAnimation from "@/public/animations/delete.json";

const Lottie = dynamic(() => import("lottie-react"), { ssr: false });

interface Lead {
  uuid: string;
  lead_number: string;
  name: string;
  email: string;
  subject: string;
  message: string;
  status: string;
  is_processed: boolean;
  created_at: string;
}

export default function AdminLead() {
  const t = useTranslations();
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [leadToDelete, setLeadToDelete] = useState<Lead | null>(null);
  const [processingLead, setProcessingLead] = useState<string | null>(null);
  const [viewModalOpen, setViewModalOpen] = useState(false);
  const [selectedLead, setSelectedLead] = useState<Lead | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);

  const fetchLeads = async () => {
    try {
      setLoading(true);
      const response = await customInstance<{
        data: {
          leads: Lead[];
          total_count: number;
          page: number;
          limit: number;
          total_pages: number;
        };
      }>({
        url: '/v1/leads',
        method: 'GET',
        params: {
          page: currentPage,
          limit: 50,
          search: searchQuery || undefined,
          sort_field: sortBy || 'created_at',
          sort_direction: 'DESC',
          ...(statusFilter && { status: statusFilter }),
        },
      });
      setLeads(response.data.leads || []);
      setTotalCount(response.data.total_count || 0);
      setTotalPages(response.data.total_pages || 1);
    } catch (error) {
      console.error('Error fetching leads:', error);
      setLeads([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLeads();
  }, [currentPage, sortBy, statusFilter]);

  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      if (currentPage === 1) {
        fetchLeads();
      } else {
        setCurrentPage(1);
      }
    }, 500);

    return () => clearTimeout(delayDebounceFn);
  }, [searchQuery]);

  const formatDate = (dateString: string) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleDateString('en-US', {
      day: 'numeric',
      month: 'short',
      year: 'numeric'
    });
  };

  const truncateMessage = (message: string, maxLength: number = 30) => {
    if (!message) return '-';
    return message.length > maxLength ? message.substring(0, maxLength) + '...' : message;
  };

  const handleViewClick = (lead: Lead) => {
    setSelectedLead(lead);
    setViewModalOpen(true);
  };

  const handleCloseViewModal = () => {
    setViewModalOpen(false);
    setSelectedLead(null);
  };

  const handleDeleteClick = (lead: Lead) => {
    setLeadToDelete(lead);
    setDeleteModalOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!leadToDelete) return;

    try {
      await customInstance({
        url: `/v1/leads/${leadToDelete.uuid}`,
        method: 'DELETE',
      });
      setDeleteModalOpen(false);
      setLeadToDelete(null);
      fetchLeads();
    } catch (error) {
      console.error('Error deleting lead:', error);
    }
  };

  const handleCancelDelete = () => {
    setDeleteModalOpen(false);
    setLeadToDelete(null);
  };

  const handleMarkAsProcessed = async (lead: Lead) => {
    try {
      setProcessingLead(lead.uuid);
      await customInstance({
        url: `/v1/leads/${lead.uuid}/process`,
        method: 'PATCH',
        data: {
          status: 'contacted',
        },
      });
      fetchLeads();
    } catch (error) {
      console.error('Error marking lead as processed:', error);
    } finally {
      setProcessingLead(null);
    }
  };

  const renderPagination = () => {
    const pages: (number | string)[] = [];

    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, '...', totalPages - 1, totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1, 2, '...', totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages);
      }
    }

    return pages.map((page, index) => (
      typeof page === 'number' ? (
        <button
          key={index}
          onClick={() => setCurrentPage(page)}
          className={`w-8 h-8 rounded-lg text-sm font-medium cursor-pointer ${
            currentPage === page
              ? 'bg-gray-100 text-gray-900'
              : 'text-gray-600 hover:bg-gray-50'
          }`}
        >
          {page}
        </button>
      ) : (
        <span key={index} className="px-2 text-gray-400">{page}</span>
      )
    ));
  };

  if (loading && leads.length === 0) {
    return (
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#3B9EC9]"></div>
        </div>
      </main>
    );
  }

  return (
    <>
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Lead Table Card */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
          {/* Table Header */}
          <div className="p-5 border-b border-gray-200">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <h3 className="text-lg font-semibold text-gray-900">
                {t("admin.lead.title")}
                {totalCount > 0 && (
                  <span className="ml-2 text-sm font-normal text-gray-500">
                    ({totalCount} {totalCount === 1 ? 'lead' : 'leads'})
                  </span>
                )}
              </h3>
              <div className="flex flex-wrap items-center gap-2">
                {/* Search */}
                <div className="relative flex-1 sm:flex-none">
                  <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                  <input
                    type="text"
                    placeholder={t("admin.common.search")}
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-9 pr-4 py-2 w-full sm:w-48 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]"
                  />
                </div>

                {/* Sort By */}
                <select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value)}
                  className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[120px] cursor-pointer"
                >
                  <option value="">{t("admin.common.sortBy")}</option>
                  <option value="created_at">{t("admin.lead.date")}</option>
                  <option value="subject">{t("admin.lead.subject")}</option>
                </select>

                {/* Status Filter */}
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[140px] cursor-pointer"
                >
                  <option value="">{t("admin.lead.allStatuses")}</option>
                  <option value="processed">{t("admin.lead.processed")}</option>
                  <option value="unprocessed">{t("admin.lead.unprocessed")}</option>
                </select>
              </div>
            </div>
          </div>

          {/* Table */}
          <div className="mx-5 mb-5 mt-5 border border-gray-300 rounded-lg overflow-hidden">
            <div className="overflow-x-auto">
            <table className="w-full border-collapse min-w-[700px]">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.lead.leadId")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.lead.user")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.lead.subject")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.lead.message")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.lead.date")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.lead.status")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-gray-300">{t("admin.lead.action")}</th>
                </tr>
              </thead>
              <tbody>
                {leads.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="px-5 py-8 text-center text-gray-500">
                      {t("admin.common.noLeadsFound")}
                    </td>
                  </tr>
                ) : (
                  leads.map((lead, index) => (
                    <tr key={lead.uuid} className="hover:bg-gray-50/50 transition">
                      <td className={`px-5 py-4 text-sm text-gray-900 border-r border-gray-300 ${index !== leads.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {lead.lead_number}
                      </td>
                      <td className={`px-5 py-4 border-r border-gray-300 ${index !== leads.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        <div>
                          <p className="text-sm font-medium text-gray-900">{lead.name}</p>
                          <p className="text-xs text-gray-500">{lead.email}</p>
                        </div>
                      </td>
                      <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== leads.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {lead.subject || '-'}
                      </td>
                      <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== leads.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {truncateMessage(lead.message)}
                      </td>
                      <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== leads.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {formatDate(lead.created_at)}
                      </td>
                      <td className={`px-5 py-4 border-r border-gray-300 ${index !== leads.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {lead.is_processed ? (
                          <span className="inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full bg-green-50 text-green-600">
                            <span className="w-1.5 h-1.5 rounded-full bg-green-500"></span>
                            {t("admin.lead.processed")}
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full bg-blue-50 text-blue-500">
                            <span className="w-1.5 h-1.5 rounded-full bg-blue-500"></span>
                            {t("admin.lead.unprocessed")}
                          </span>
                        )}
                      </td>
                      <td className={`px-5 py-4 ${index !== leads.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => handleViewClick(lead)}
                            className="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center text-blue-400 hover:bg-blue-100 hover:text-blue-600 transition cursor-pointer"
                            title={t("admin.common.view")}
                          >
                            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" />
                              <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            </svg>
                          </button>
                          {!lead.is_processed && (
                            <button
                              onClick={() => handleMarkAsProcessed(lead)}
                              disabled={processingLead === lead.uuid}
                              className="w-9 h-9 rounded-lg bg-green-50 flex items-center justify-center text-green-400 hover:bg-green-100 hover:text-green-600 transition disabled:opacity-50 cursor-pointer"
                              title={t("admin.lead.markProcessed")}
                            >
                              {processingLead === lead.uuid ? (
                                <div className="w-4 h-4 border-2 border-green-400 border-t-transparent rounded-full animate-spin"></div>
                              ) : (
                                <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                                </svg>
                              )}
                            </button>
                          )}
                          <button
                            onClick={() => handleDeleteClick(lead)}
                            className="w-9 h-9 rounded-lg bg-red-50 flex items-center justify-center text-red-400 hover:bg-red-100 hover:text-red-600 transition cursor-pointer"
                            title={t("admin.common.delete")}
                          >
                            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
            </div>
          </div>

          {/* Pagination */}


          {totalPages > 1 && (


          <div className="px-5 py-4 border-t border-gray-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <button
              onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
              disabled={currentPage === 1}
              className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
              {t("admin.common.previous")}
            </button>

            <div className="flex items-center gap-1">
              {renderPagination()}
            </div>

            <button
              onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
              disabled={currentPage === totalPages}
              className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              {t("admin.common.next")}
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </button>
          </div>
          )}
        </div>
      </main>

      {/* View Lead Detail Modal */}
      {viewModalOpen && selectedLead && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ animation: 'fadeIn 0.2s ease-out' }}
        >
          <style dangerouslySetInnerHTML={{ __html: `
            @keyframes fadeIn {
              from { opacity: 0; }
              to { opacity: 1; }
            }
            @keyframes scaleIn {
              from { opacity: 0; transform: scale(0.9) translateY(10px); }
              to { opacity: 1; transform: scale(1) translateY(0); }
            }
          `}} />

          {/* Backdrop */}
          <div
            className="absolute inset-0 bg-black/30"
            style={{ animation: 'fadeIn 0.2s ease-out' }}
            onClick={handleCloseViewModal}
          ></div>

          {/* Modal */}
          <div
            className="relative bg-white rounded-2xl shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-hidden"
            style={{ animation: 'scaleIn 0.3s ease-out' }}
          >
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
              <h3 className="text-xl font-semibold text-gray-900">
                {t("admin.modals.leadDetails")}
              </h3>
              <button
                onClick={handleCloseViewModal}
                className="text-gray-400 hover:text-gray-600 transition cursor-pointer"
              >
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* Content */}
            <div className="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
              {/* Lead ID and Date */}
              <div className="flex items-center gap-4 mb-6">
                <span className="px-3 py-1 bg-blue-50 text-blue-600 text-sm font-medium rounded-full">
                  {selectedLead.lead_number}
                </span>
                <span className="text-sm text-gray-500">
                  {formatDate(selectedLead.created_at)}
                </span>
                {selectedLead.is_processed && (
                  <span className="px-3 py-1 bg-green-50 text-green-600 text-sm font-medium rounded-full">
                    {t("admin.modals.processed")}
                  </span>
                )}
              </div>

              {/* User Info */}
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-500 mb-2">
                  {t("admin.lead.user")}
                </label>
                <div className="bg-gray-50 rounded-lg p-4">
                  <p className="text-base font-medium text-gray-900">{selectedLead.name}</p>
                  <p className="text-sm text-gray-500">{selectedLead.email}</p>
                </div>
              </div>

              {/* Subject */}
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-500 mb-2">
                  {t("admin.lead.subject")}
                </label>
                <div className="bg-gray-50 rounded-lg p-4">
                  <p className="text-base text-gray-900 break-words">{selectedLead.subject || '-'}</p>
                </div>
              </div>

              {/* Message */}
              <div>
                <label className="block text-sm font-medium text-gray-500 mb-2">
                  {t("admin.lead.message")}
                </label>
                <div className="bg-gray-50 rounded-lg p-4">
                  <p className="text-base text-gray-900 whitespace-pre-wrap break-words">
                    {selectedLead.message || '-'}
                  </p>
                </div>
              </div>
            </div>

            {/* Footer */}
            <div className="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
              {!selectedLead.is_processed && (
                <button
                  onClick={() => {
                    handleMarkAsProcessed(selectedLead);
                    handleCloseViewModal();
                  }}
                  className="px-6 py-2.5 bg-[#3B9EC9] rounded-full text-white font-medium hover:bg-[#2B8EB9] transition cursor-pointer"
                >
                  {t("admin.modals.markProcessed")}
                </button>
              )}
              <button
                onClick={handleCloseViewModal}
                className="px-6 py-2.5 border border-gray-300 rounded-full text-gray-600 font-medium hover:bg-gray-50 transition cursor-pointer"
              >
                {t("admin.modals.close")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {deleteModalOpen && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ animation: 'fadeIn 0.2s ease-out' }}
        >
          <style dangerouslySetInnerHTML={{ __html: `
            @keyframes fadeIn {
              from { opacity: 0; }
              to { opacity: 1; }
            }
            @keyframes scaleIn {
              from { opacity: 0; transform: scale(0.9) translateY(10px); }
              to { opacity: 1; transform: scale(1) translateY(0); }
            }
          `}} />

          {/* Backdrop */}
          <div
            className="absolute inset-0 bg-black/30"
            style={{ animation: 'fadeIn 0.2s ease-out' }}
            onClick={handleCancelDelete}
          ></div>

          {/* Modal */}
          <div
            className="relative bg-white rounded-2xl shadow-xl w-full max-w-md mx-4 p-8 pt-12"
            style={{ animation: 'scaleIn 0.3s ease-out' }}
          >
            {/* Close button */}
            <button
              onClick={handleCancelDelete}
              className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition cursor-pointer"
            >
              <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>

            {/* Icon - Lottie Animation */}
            <div className="flex justify-center mb-6">
              <div className="w-36 h-36">
                <Lottie
                  animationData={deleteAnimation}
                  loop={false}
                  autoplay={true}
                />
              </div>
            </div>

            {/* Content */}
            <div className="text-center mb-8">
              <h3 className="text-2xl font-semibold text-[#E05A5A] mb-3">{t("admin.modals.removeLead")}</h3>
              <p className="text-gray-500 text-lg">
                {t("admin.modals.removeLeadConfirm")}
              </p>
            </div>

            {/* Actions */}
            <div className="flex gap-4 justify-center">
              <button
                onClick={handleCancelDelete}
                className="px-10 py-3 border border-gray-300 rounded-full text-gray-600 font-medium hover:bg-gray-50 transition cursor-pointer"
              >
                {t("admin.modals.close")}
              </button>
              <button
                onClick={handleConfirmDelete}
                className="px-10 py-3 bg-[#E05A5A] rounded-full text-white font-medium hover:bg-[#D04A4A] transition cursor-pointer"
              >
                {t("admin.modals.remove")}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
