"use client";
import React, { useState, useEffect } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchClients, createClient, updateClient, deleteClient } from "@/store/slices/clientSlice";
import { Client } from "@/types";
import { Eye, Pencil, Trash2, Search, Plus, Mail, Phone, Globe, Building2, User, ChevronDown } from "lucide-react";
import DataTable from "react-data-table-component";
import { Modal } from "@/components/common/modal";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";
import { useModal } from "@/hooks/useModal";

export default function ClientsPage() {
  const dispatch = useAppDispatch();
  const { clients, meta, isLoading } = useAppSelector((state) => state.clients);
  const authUser = useAppSelector((state: any) => state.auth.user);

  const isAdmin = authUser?.role?.toLowerCase() === 'admin';
  const canView = true;
  const canEdit = isAdmin;
  const canDelete = isAdmin;
  const canCreate = isAdmin;

  const [searchText, setSearchText] = useState("");
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [resetPaginationToggle, setResetPaginationToggle] = useState(false);
  const { isOpen, openModal, closeModal } = useModal();
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);

  const { register, handleSubmit, reset, setError, formState: { errors } } = useForm<Partial<Client>>({
    defaultValues: {
      isActive: true,
    }
  });

  useEffect(() => {
    const timer = setTimeout(() => {
      dispatch(fetchClients({ search: searchText, page: currentPage, limit: rowsPerPage }));
    }, 500);
    return () => clearTimeout(timer);
  }, [dispatch, searchText, currentPage, rowsPerPage]);

  const handleOpenModal = () => {
    reset({
      name: "",
      code: "",
      contactName: "",
      contactEmail: "",
      contactPhone: "",
      companyWebsite: "",
      billingAddress: "",
      notes: "",
      isActive: true,
    });
    setSelectedClient(null);
    openModal();
  };

  const handleEdit = (client: Client) => {
    setSelectedClient(client);
    reset(client);
    openModal();
  };

  const handleView = (client: Client) => {
    setSelectedClient(client);
    setIsViewModalOpen(true);
  };

  const handleDelete = (client: Client) => {
    setSelectedClient(client);
    setIsDeleteModalOpen(true);
  };

  const onSubmit = async (data: Partial<Client>) => {
    try {
      // Fix boolean casting for select input
      data.isActive = String(data.isActive) === "true";

      if (selectedClient?.id) {
        await dispatch(updateClient({ id: selectedClient.id, data })).unwrap();
        toast.success("Client updated successfully");
      } else {
        await dispatch(createClient(data)).unwrap();
        toast.success("Client created successfully");
      }
      dispatch(fetchClients({}));
      closeModal();
    } catch (error: any) {
      if (error?.errors && Array.isArray(error.errors)) {
        error.errors.forEach((err: any) => {
          if (err.field) {
            setError(err.field as keyof Client, { type: 'server', message: err.message });
          }
        });
      } else {
        toast.error(error?.message || error || "An error occurred");
      }
    }
  };

  const confirmDelete = async () => {
    if (selectedClient) {
      try {
        await dispatch(deleteClient(selectedClient.id)).unwrap();
        toast.success("Client deleted successfully");
        setIsDeleteModalOpen(false);
      } catch (error: any) {
        toast.error(error || "Failed to delete client");
      }
    }
  };

  const columns = [
    {
      name: 'S.No',
      selector: (row: Client, index?: number) => (index || 0) + 1 + (currentPage - 1) * rowsPerPage,
      sortable: false,
      width: '70px',
      cell: (row: Client, index?: number) => (
        <span className="text-sm font-medium text-gray-500">
          {(index || 0) + 1 + (currentPage - 1) * rowsPerPage}
        </span>
      )
    },
    {
      name: 'Client Details',
      selector: (row: Client) => row.name,
      sortable: true,
      minWidth: "250px",
      cell: (row: Client) => (
        <div className="flex flex-col py-2">
          <span className="font-semibold text-brand-950 text-sm">{row.name}</span>
          {row.code && <span className="text-xs text-gray-500 mt-0.5">Code: {row.code}</span>}
        </div>
      )
    },
    {
      name: 'Contact Person',
      selector: (row: Client) => row.contactName || '',
      sortable: true,
      minWidth: "150px",
      cell: (row: Client) => (
        <span className="text-sm text-gray-700">{row.contactName || 'N/A'}</span>
      )
    },
    {
      name: 'Email',
      selector: (row: Client) => row.contactEmail || '',
      sortable: true,
      minWidth: "200px",
      cell: (row: Client) => (
        <div className="flex items-center gap-1.5 text-sm text-gray-700">
          {row.contactEmail ? (
            <>
              <Mail size={14} className="text-gray-400" />
              {row.contactEmail}
            </>
          ) : 'N/A'}
        </div>
      )
    },
    {
      name: 'Phone',
      selector: (row: Client) => row.contactPhone || '',
      sortable: true,
      minWidth: "150px",
      cell: (row: Client) => (
        <div className="flex items-center gap-1.5 text-sm text-gray-700">
          {row.contactPhone ? (
            <>
              <Phone size={14} className="text-gray-400" />
              {row.contactPhone}
            </>
          ) : 'N/A'}
        </div>
      )
    },
    {
      name: 'Status',
      selector: (row: Client) => row.isActive ? "Active" : "Inactive",
      sortable: true,
      minWidth: "120px",
      cell: (row: Client) => (
        <span className={`px-2.5 py-1 text-xs font-medium rounded-full ${row.isActive ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
          {row.isActive ? "Active" : "Inactive"}
        </span>
      )
    }
  ];

  if (canView || canEdit || canDelete) {
    columns.push({
      name: 'Action',
      sortable: false,
      minWidth: "140px",
      cell: (row: Client) => (
        <div className="flex justify-start gap-2">
          {canView && (
            <button
              onClick={() => handleView(row)}
              className="w-8 h-8 rounded-md bg-brand-950/10 flex items-center justify-center text-brand-950 hover:bg-brand-950/20 transition-colors"
              title="View Client"
            >
              <Eye size={16} />
            </button>
          )}
          {canEdit && (
            <button
              onClick={() => handleEdit(row)}
              className="w-8 h-8 rounded-md bg-amber-500/10 flex items-center justify-center text-amber-600 hover:bg-amber-500/20 transition-colors"
              title="Edit Client"
            >
              <Pencil size={16} />
            </button>
          )}
          {canDelete && (
            <button
              onClick={() => handleDelete(row)}
              className="w-8 h-8 rounded-md bg-red-500/10 flex items-center justify-center text-red-500 hover:bg-red-500/20 transition-colors"
              title="Delete Client"
            >
              <Trash2 size={16} />
            </button>
          )}
        </div>
      )
    } as any);
  }

  return (
    <div className="min-h-screen">
      <div className="mx-auto max-w-[1500px] space-y-6">
        <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
          <h1 className="text-xl lg:text-2xl font-medium text-brand-950">Clients</h1>
          <div className="flex items-center gap-3">
            {canCreate && (
              <button
                onClick={handleOpenModal}
                className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-2.5 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500"
              >
                <Plus size={18} />
                <span>Add Client</span>
              </button>
            )}
          </div>
        </div>

        {/* Table Container */}
        <div className="rounded-xl bg-white p-6 shadow-theme-md">
          <div className="md:border border-gray-200 rounded-lg overflow-hidden">
            <div className="flex items-center justify-between md:border-b md:px-4 pb-4 md:py-4">
              <div className="hidden md:flex items-center gap-2">
                <span className="text-sm font-normal text-gray-500 block">Show</span>
                <select
                  value={rowsPerPage}
                  onChange={(e) => {
                    setRowsPerPage(Number(e.target.value));
                    setCurrentPage(1);
                    setResetPaginationToggle(!resetPaginationToggle);
                  }}
                  className="rounded-lg border px-3 py-1.5 text-sm outline-none text-gray-700"
                >
                  <option value={10}>10</option>
                  <option value={20}>20</option>
                  <option value={50}>50</option>
                </select>
                <span className="text-sm font-normal text-gray-500">entries</span>
              </div>
              <div className="relative block w-full sm:w-auto">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                <input
                  type="text"
                  placeholder="Search clients..."
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  className="h-10 w-full rounded-lg border appearance-none py-2 pl-9 pr-4 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 border-gray-300 outline-none"
                />
              </div>
            </div>

            <div className="overflow-x-auto">
              <DataTable
                key={`table-${rowsPerPage}`}
                columns={columns}
                data={clients}
                pagination
                paginationServer
                paginationTotalRows={meta?.total || 0}
                paginationResetDefaultPage={resetPaginationToggle}
                paginationPerPage={rowsPerPage}
                paginationComponentOptions={{ noRowsPerPage: true }}
                onChangePage={(page) => setCurrentPage(page)}
                onChangeRowsPerPage={(newPerPage, page) => {
                  setRowsPerPage(newPerPage);
                  setCurrentPage(page);
                }}
                highlightOnHover
                progressPending={isLoading}
                customStyles={{
                  headRow: {
                    style: {
                      backgroundColor: '#ffffff',
                      color: '#1E293B',
                      fontWeight: 600,
                      fontSize: '14px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                  rows: {
                    style: {
                      fontSize: '14px',
                      color: '#475569',
                      minHeight: '60px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                }}
              />
            </div>
          </div>
        </div>

        {/* Create/Edit Modal */}
        <Modal isOpen={isOpen} onClose={closeModal} className="max-w-[700px] m-4">
          <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
            <div className="px-2 pr-14">
              <h4 className="mb-2 text-xl lg:text-2xl font-semibold text-brand-950">
                {selectedClient ? "Edit Client" : "Add New Client"}
              </h4>
              {/* <p className="mb-6 text-sm text-gray-500 lg:mb-7">
                {selectedClient?.id && <span>{selectedClient.id}</span>}
              </p> */}
            </div>

            <form onSubmit={handleSubmit(onSubmit)} className="px-2 space-y-6 lg:space-y-5" autoComplete="off">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Client Name <span className="text-red-500">*</span></label>
                  <div className="relative">
                    <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                    <input
                      {...register("name", {
                        required: "Client name is required",
                        minLength: { value: 2, message: "Client name must be at least 2 characters" },
                        maxLength: { value: 100, message: "Client name must be less than 100 characters" }
                      })}
                      className={`h-11 w-full rounded-lg border pl-9 pr-4 text-sm outline-none ${errors.name ? 'border-red-500 focus:border-red-500' : 'border-gray-300 focus:border-brand-950'}`}
                      placeholder="e.g. Acme Corp"
                      autoComplete="off"
                    />
                  </div>
                  {errors.name && <span className="text-xs text-red-500 mt-1">{errors.name.message}</span>}
                </div>

                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Client Code <span className="text-red-500">*</span></label>
                  <input
                    {...register("code", {
                      required: "Client code is required",
                      maxLength: { value: 50, message: "Code must be less than 50 characters" }
                    })}
                    className={`h-11 w-full rounded-lg border px-4 text-sm outline-none ${errors.code ? 'border-red-500 focus:border-red-500' : 'border-gray-300 focus:border-brand-950'}`}
                    placeholder="e.g. ACME"
                    autoComplete="off"
                  />
                  {errors.code && <span className="text-xs text-red-500 mt-1">{errors.code.message}</span>}
                </div>

                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Contact Person <span className="text-red-500">*</span></label>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                    <input
                      {...register("contactName", { required: "Contact person is required" })}
                      className={`h-11 w-full rounded-lg border pl-9 pr-4 text-sm outline-none ${errors.contactName ? 'border-red-500 focus:border-red-500' : 'border-gray-300 focus:border-brand-950'}`}
                      placeholder="John Doe"
                      autoComplete="off"
                    />
                  </div>
                  {errors.contactName && <span className="text-xs text-red-500 mt-1">{errors.contactName.message}</span>}
                </div>

                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Contact Email <span className="text-red-500">*</span></label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                    <input
                      type="email"
                      {...register("contactEmail", { required: "Contact email is required", pattern: { value: /^\S+@\S+$/i, message: "Invalid email" } })}
                      className={`h-11 w-full rounded-lg border pl-9 pr-4 text-sm outline-none ${errors.contactEmail ? 'border-red-500 focus:border-red-500' : 'border-gray-300 focus:border-brand-950'}`}
                      placeholder="john@example.com"
                      autoComplete="off"
                    />
                  </div>
                  {errors.contactEmail && <span className="text-xs text-red-500 mt-1">{errors.contactEmail.message}</span>}
                </div>

                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Contact Phone <span className="text-red-500">*</span></label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                    <input
                      {...register("contactPhone", { required: "Contact phone is required" })}
                      className={`h-11 w-full rounded-lg border pl-9 pr-4 text-sm outline-none ${errors.contactPhone ? 'border-red-500 focus:border-red-500' : 'border-gray-300 focus:border-brand-950'}`}
                      placeholder="+1 (555) 000-0000"
                      autoComplete="off"
                    />
                  </div>
                  {errors.contactPhone && <span className="text-xs text-red-500 mt-1">{errors.contactPhone.message}</span>}
                </div>

                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Company Website</label>
                  <div className="relative">
                    <Globe className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                    <input
                      {...register("companyWebsite")}
                      className="h-11 w-full rounded-lg border border-gray-300 pl-9 pr-4 text-sm outline-none focus:border-brand-950"
                      placeholder="https://acme.com"
                    />
                  </div>
                </div>

                <div className="md:col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Billing Address</label>
                  <textarea
                    {...register("billingAddress")}
                    className="w-full rounded-lg border border-gray-300 p-3 text-sm outline-none focus:border-brand-950 min-h-[80px]"
                    placeholder="123 Business Rd..."
                  />
                </div>

                <div className="md:col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Notes</label>
                  <textarea
                    {...register("notes")}
                    className="w-full rounded-lg border border-gray-300 p-3 text-sm outline-none focus:border-brand-950 min-h-[80px]"
                    placeholder="Any additional information..."
                  />
                </div>

                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Status</label>
                  <div className="relative">
                    <select
                      {...register("isActive")}
                      className="h-11 w-full rounded-lg border border-gray-300 px-4 text-sm outline-none focus:border-brand-950 appearance-none"
                    >
                      <option value="true">Active</option>
                      <option value="false">Inactive</option>
                    </select>
                    <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                  </div>
                </div>
              </div>

              <div className="flex items-center gap-3 mt-6 lg:justify-end">
                <button
                  type="button"
                  onClick={closeModal}
                  className="flex items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-gray-700"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 disabled:bg-yellow-500 disabled:opacity-50"
                >
                  {selectedClient ? "Save Changes" : "Create Client"}
                </button>
              </div>
            </form>
          </div>
        </Modal>

        {/* View Modal */}
        <Modal isOpen={isViewModalOpen} onClose={() => setIsViewModalOpen(false)} className="max-w-[600px] m-4">
          {selectedClient && (
            <div className="w-full max-w-[600px] rounded-3xl bg-white p-6 lg:p-8">
              <div className="flex justify-between items-start mb-6 pr-12">
                <div>
                  <h4 className="text-2xl font-semibold text-brand-950 mb-1">{selectedClient.name}</h4>
                  {selectedClient.code && <span className="text-sm font-medium text-gray-500">Code: {selectedClient.code}</span>}
                </div>
                <span className={`px-3 py-1 text-xs font-semibold rounded-full ${selectedClient.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                  {selectedClient.isActive ? "Active" : "Inactive"}
                </span>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div className="space-y-4">
                  <div>
                    <span className="text-xs font-medium text-gray-500 uppercase tracking-wider block mb-1">Contact Person</span>
                    <p className="text-sm text-gray-900 font-medium">{selectedClient.contactName || 'N/A'}</p>
                  </div>
                  <div>
                    <span className="text-xs font-medium text-gray-500 uppercase tracking-wider block mb-1">Email</span>
                    <p className="text-sm text-gray-900">{selectedClient.contactEmail || 'N/A'}</p>
                  </div>
                  <div>
                    <span className="text-xs font-medium text-gray-500 uppercase tracking-wider block mb-1">Phone</span>
                    <p className="text-sm text-gray-900">{selectedClient.contactPhone || 'N/A'}</p>
                  </div>
                </div>

                <div className="space-y-4">
                  <div>
                    <span className="text-xs font-medium text-gray-500 uppercase tracking-wider block mb-1">Website</span>
                    <p className="text-sm text-blue-600 hover:underline">
                      {selectedClient.companyWebsite ? (
                        <a href={selectedClient.companyWebsite} target="_blank" rel="noreferrer">{selectedClient.companyWebsite}</a>
                      ) : 'N/A'}
                    </p>
                  </div>
                  <div>
                    <span className="text-xs font-medium text-gray-500 uppercase tracking-wider block mb-1">Billing Address</span>
                    <p className="text-sm text-gray-900 whitespace-pre-wrap">{selectedClient.billingAddress || 'N/A'}</p>
                  </div>
                </div>
              </div>

              {selectedClient.notes && (
                <div className="mb-6 pt-6 border-t border-gray-100">
                  <span className="text-xs font-medium text-gray-500 uppercase tracking-wider block mb-2">Notes</span>
                  <p className="text-sm text-gray-700 whitespace-pre-wrap bg-gray-50 p-4 rounded-lg">{selectedClient.notes}</p>
                </div>
              )}

              <div className="flex justify-end pt-4 border-t border-gray-100">
                <button
                  onClick={() => setIsViewModalOpen(false)}
                  className="px-5 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
                >
                  Close
                </button>
              </div>
            </div>
          )}
        </Modal>

        {/* Delete Confirmation Modal */}
        <Modal isOpen={isDeleteModalOpen} onClose={() => setIsDeleteModalOpen(false)} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
            <div className="px-2 text-center">
              <h4 className="text-xl lg:text-2xl font-semibold text-brand-950 mb-2">
                Confirm Delete
              </h4>
              <p className="mb-6 text-sm text-gray-500 lg:mb-7">
                Are you sure you want to delete
                <span className="font-semibold pl-0.5">
                  {selectedClient?.name}
                </span>?
              </p>
            </div>
            <div className="flex items-center gap-3 mt-6 justify-center">
              <button
                onClick={() => setIsDeleteModalOpen(false)}
                className="flex items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-gray-700"
              >
                Cancel
              </button>
              <button
                onClick={confirmDelete}
                className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 disabled:bg-yellow-500 disabled:opacity-50"
              >
                Delete
              </button>
            </div>
          </div>
        </Modal>

      </div>
    </div>
  );
}
