import React, { useEffect, useState, useCallback } from "react";
import {
  Plus,
  Trash2,
  Save,
  X,
  Check,
  IndianRupee,
  Edit2,
  Search as SearchIcon,
  Building2,
  Link2,
  Eye,
  EyeOff,
  Building,
} from "lucide-react";
import { ISubscriptionPlan } from "@/types";
import {
  Button,
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Tag,
  Select,
  Table,
  Pagination,
  Radio,
  Switch,
  Tooltip
} from "antd";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import Modal from "@/components/shared/Modal";
import { useNavigate } from "react-router-dom";
import ROUTE_CONSTANTS from "@/constants/route.constants";

const { TextArea } = Input;

interface PlanFormProps {
  mode: "add" | "edit";
  initialValues: any;
  onSave: (data: any) => void;
  onCancel: () => void;
  loading?: boolean;
  institutions: { id: string; name: string }[];
}


export default function Subscription() {
  const navigate = useNavigate();
  const [plans, setPlans] = useState<ISubscriptionPlan[]>([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState("");
  const [selectedInstitutionId, setSelectedInstitutionId] = useState<string | undefined>(undefined);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [meta, setMeta] = useState<{ total: number; page: number; limit: number; totalPages: number } | null>(null);
  const [institutions, setInstitutions] = useState<{ id: string; name: string }[]>([]);
  const [institutionPage, setInstitutionPage] = useState(1);
  const [hasMoreInstitutions, setHasMoreInstitutions] = useState(true);
  const [institutionLoading, setInstitutionLoading] = useState(false);
  const [institutionMapPlan, setInstitutionMapPlan] = useState<ISubscriptionPlan | null>(null);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalMode, setModalMode] = useState<"add" | "edit">("add");
  const [selectedPlan, setSelectedPlan] = useState<ISubscriptionPlan | null>(
    null,
  );

  const fetchInstitutions = async (page = 1) => {
    if (institutionLoading || (!hasMoreInstitutions && page > 1)) return;

    setInstitutionLoading(true);
    try {
      const res = await API_Instance.get(API_Constants.institutionsList, {
        params: { page, limit: 10 },
      });
      const nextInstitutions = res.data.data ?? [];
      setInstitutions((prev) => (page === 1 ? nextInstitutions : [...prev, ...nextInstitutions]));
      setInstitutionPage(page);
      setHasMoreInstitutions(nextInstitutions.length === 10);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setInstitutionLoading(false);
    }
  };

  const handleOpenManageInstitutions = (plan: ISubscriptionPlan) => {
    setInstitutionMapPlan(plan);
  };

  const fetchPlans = async (page = currentPage, limit = pageSize) => {
    setLoading(true);
    try {
      const res = await API_Instance.get(API_Constants.subscriptionPlans, {
        params: {
          search,
          institutionId: selectedInstitutionId || undefined,
          page,
          limit,
        },
      });
      setPlans(res.data.data || []);
      setMeta(res.data.meta || null);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchInstitutions(1);
  }, []);

  useEffect(() => {
    fetchPlans(currentPage, pageSize);
  }, [search, selectedInstitutionId, currentPage, pageSize]);

  const totalCount = meta?.total ?? plans.length;

  const handleOpenAdd = () => {
    setModalMode("add");
    setSelectedPlan(null);
    setIsModalOpen(true);
  };

  const handleOpenEdit = (plan: ISubscriptionPlan) => {
    setModalMode("edit");
    setSelectedPlan(plan);
    setIsModalOpen(true);
  };

  const handleSave = async (values: any) => {
    try {
      if (modalMode === "edit" && selectedPlan) {
        await API_Instance.put(
          `${API_Constants.subscriptionPlans}/${selectedPlan.id}`,
          values,
        );
        toast.success("Plan updated successfully");
      } else {
        await API_Instance.post(API_Constants.subscriptionPlans, values);
        toast.success("Plan created successfully");
      }
      setIsModalOpen(false);
      setCurrentPage(1);
      fetchPlans(1, pageSize);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await API_Instance.delete(`${API_Constants.subscriptionPlans}/${id}?deleteAll=true`);
      toast.success("Plan deleted successfully");
      fetchPlans(1, pageSize);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    }
  };

  return (
    <div className="mx-auto px-3 py-6 max-w-[1600px] min-h-screen">
      <div className="flex flex-col lg:flex-row justify-between items-start gap-6 mb-6">
        <div>
          <h2 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
            <IndianRupee className="text-blue-600" />
            Subscription Packs
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            Design and manage your subscription tiers and pricing models.
          </p>
        </div>

        <Button
          type="primary"
          onClick={handleOpenAdd}
          icon={<Plus size={20} />}
          className="h-11 px-6 rounded-xl bg-blue-600 hover:bg-blue-700 flex items-center"
        >
          Create Pack
        </Button>
      </div>

      <div className="bg-white rounded-3xl shadow-sm p-6">
        <div className="flex flex-col xl:flex-row items-start xl:items-center justify-between gap-4 mb-6">
          <div className="flex flex-wrap gap-4 items-center w-full xl:w-auto">
            <Input
              placeholder="Search plans..."
              prefix={<SearchIcon size={18} className="text-slate-400" />}
              allowClear
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setCurrentPage(1);
              }}
              className="w-full md:w-64 rounded-md border-slate-300"
            />
            <Select
              allowClear
              showSearch
              placeholder="Filter by institution"
              className="w-full md:w-64 rounded-xl"
              value={selectedInstitutionId || undefined}
              loading={institutionLoading}
              onPopupScroll={(e) => {
                const target = e.currentTarget;
                if (Math.ceil(target.scrollTop + target.offsetHeight) >= target.scrollHeight) {
                  if (hasMoreInstitutions && !institutionLoading) {
                    void fetchInstitutions(institutionPage + 1);
                  }
                }
              }}
              onChange={(value) => {
                setSelectedInstitutionId(value || undefined);
                setCurrentPage(1);
              }}
              onSearch={(value) => {
                if (!value) {
                  setInstitutions([]);
                  setInstitutionPage(1);
                  setHasMoreInstitutions(true);
                  void fetchInstitutions(1);
                }
              }}
              options={institutions.map((inst) => ({ label: inst.name, value: inst.id }))}
            />
          </div>
          <div className="text-sm text-slate-500">
            Total Plans: {totalCount}
          </div>
        </div>

        {/* GRID */}
        {loading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-3">
            {[1, 2, 3, 4].map((i) => (
              <div
                key={i}
                className="h-[200px] bg-gray-50 rounded-xl animate-pulse"
              />
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-3">
            {plans.length > 0
              ? plans.map((plan) => {
                const saving = ((Number(plan.actualPrice) * Number(plan.discountPercentage)) / 100).toFixed(2);
                return (
                  <div
                    key={plan.id}
                    className="group rounded-xl bg-white border border-slate-200 shadow-sm hover:shadow-md hover:border-blue-200 transition-all duration-200 flex flex-col"
                  >
                    {/* Header */}
                    <div className="p-3.5 pb-2 flex items-start justify-between gap-2">
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-1.5 mb-0.5">
                          <Building2 size={11} className="text-slate-400 shrink-0" />
                          <span className="text-[10px] font-medium text-slate-400 truncate">
                            {plan.institutionSubscriptions?.length
                              ? `${plan.institutionSubscriptions.length} institution${plan.institutionSubscriptions.length > 1 ? "s" : ""} published`
                              : `0 institution published`
                            }
                          </span>
                        </div>
                        <h3 className="text-[15px] font-bold text-slate-800 truncate">
                          {plan.planName}
                        </h3>
                        <div className="flex flex-wrap gap-1.5 mt-1">
                          <Tag className="m-0 text-[9px] px-2 py-0 rounded-full border-0 bg-blue-50 text-blue-600 font-semibold uppercase leading-4">
                            {plan.planType}
                          </Tag>
                          <span className="text-[9px] font-semibold text-slate-500 bg-slate-50 px-2 py-0 rounded-full border border-slate-100 leading-4">
                            {plan.duration}d
                          </span>
                        </div>
                      </div>
                      <div className="flex gap-0.5 shrink-0">
                        <button
                          onClick={() => handleOpenManageInstitutions(plan)}
                          title="Manage Institution Mappings"
                          className="p-1.5 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-all"
                        >
                          <Link2 size={14} />
                        </button>
                        <button
                          onClick={() => handleOpenEdit(plan)}
                          className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-all"
                        >
                          <Edit2 size={14} />
                        </button>
                        <Popconfirm
                          title="Delete Plan"
                          description="Are you sure?"
                          onConfirm={() => handleDelete(plan.id)}
                          okText="Delete"
                          cancelText="Cancel"
                          okButtonProps={{ danger: true }}
                        >
                          <button className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all">
                            <Trash2 size={14} />
                          </button>
                        </Popconfirm>
                      </div>
                    </div>

                    {/* Price row */}
                    <div className="p-2">
                      <div className="px-3.5 py-2 bg-gradient-to-r from-slate-50 to-blue-50/30 border border-slate-100 rounded ">
                        <div className="flex items-baseline justify-between">
                          <div className="flex items-baseline gap-1">
                            <span className="text-[10px] font-bold text-slate-400">Rs.</span>
                            <span className="text-xl font-extrabold text-slate-900 tracking-tight">
                              {Math.floor(plan.priceAfterDiscount)}
                            </span>
                            <span className="text-[10px] font-bold text-slate-400">
                              .{Number(plan.priceAfterDiscount).toFixed(2).split(".")[1]}
                            </span>
                          </div>
                          <div className="text-right">
                            {Number(plan.discountPercentage) > 0 && (
                              <div className="flex items-center gap-1.5">
                                <span className="text-[10px] line-through text-slate-400">Rs.{Number(plan.actualPrice).toLocaleString()}</span>
                                <span className="text-[9px] font-bold text-green-600 bg-green-50 px-1.5 py-0 rounded border border-green-100">-{plan.discountPercentage}%</span>
                              </div>
                            )}
                            <div className="text-[9px] text-slate-400 font-medium">incl. {plan.gstPercentage}% GST</div>
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Description */}
                    {plan.description && (
                      <p className="px-3.5 pt-2 text-[11px] text-slate-500 leading-relaxed line-clamp-2">
                        {plan.description}
                      </p>
                    )}

                    {/* Features */}
                    {plan.features.length > 0 && (
                      <div className="px-3.5 pt-2 pb-1.5 flex-1">
                        <div className="flex flex-wrap gap-x-2 gap-y-1">
                          {plan.features.slice(0, 4).map((feature, index) => (
                            <span
                              key={index}
                              className="inline-flex items-center gap-1 text-[10px] text-slate-600"
                            >
                              <Check size={10} className="text-green-500 shrink-0" strokeWidth={2.5} />
                              <span className="truncate max-w-[120px]">{feature}</span>
                            </span>
                          ))}
                          {plan.features.length > 4 && (
                            <span className="text-[9px] font-semibold text-blue-500">
                              +{plan.features.length - 4} more
                            </span>
                          )}
                        </div>
                      </div>
                    )}

                    {/* Footer */}
                    <div className="px-3.5 py-2 border-t border-slate-100 flex items-center justify-between">
                      <span
                        className="text-[10px] font-medium text-blue-400 hover:text-blue-600 cursor-pointer transition-colors"
                        onClick={() => {
                          navigate(
                            ROUTE_CONSTANTS.SubscriptionsHistory.replace(
                              ":slug",
                              plan.planType,
                            ),
                          );
                        }}
                      >
                        History →
                      </span>
                      {/* <span className="text-[9px] text-slate-300">{plan.duration} day plan</span> */}
                    </div>
                  </div>
                );
              })
              : !loading && (
                <div className="col-span-full flex flex-col items-center justify-center py-24 text-slate-400 border-2 border-dashed border-slate-100 rounded-[2rem] bg-slate-50/30">
                  <div className="p-6 bg-white rounded-full shadow-sm mb-4">
                    <Trash2 size={48} className="opacity-20" />
                  </div>
                  <h3 className="text-lg font-bold text-slate-600">
                    No subscription packs found
                  </h3>
                  <p className="text-sm mt-1">
                    Try adjusting your search filters.
                  </p>
                </div>
              )}
          </div>
        )}

        {meta && (
          <div className="flex justify-end mt-4">
            <Pagination
              current={currentPage}
              pageSize={pageSize}
              total={meta.total}
              onChange={(page, size) => {
                setCurrentPage(page);
                setPageSize(size || 10);
              }}
              showSizeChanger
              hideOnSinglePage={false}
              pageSizeOptions={["10", "20", "50", "100"]}
              showTotal={(total) => `Total ${total} plans`}
            />
          </div>
        )}
      </div>

      {/* FORM MODAL */}
      <Modal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={
          modalMode === "add"
            ? "Create New Subscription Pack"
            : "Edit Subscription Pack"
        }
        className="max-w-3xl"
      >
        <PlanFormCard
          mode={modalMode}
          initialValues={
            selectedPlan
              ? {
                ...selectedPlan,
                institutionIds: selectedPlan?.institutionSubscriptions?.map((is: any) => is.institutionId) || [],
              }
              : {
                planType: "",
                planName: "",
                actualPrice: 0,
                discountPercentage: 0,
                gstPercentage: 18,
                duration: 30,
                description: "",
                features: [],
                institutionIds: [],
              }
          }
          onSave={handleSave}
          onCancel={() => setIsModalOpen(false)}
          institutions={institutions}
        />
      </Modal>

      {/* MANAGE INSTITUTIONS MODAL */}
      {institutionMapPlan && (
        <ManageInstitutionsModal
          plan={institutionMapPlan}
          onClose={() => {
            setInstitutionMapPlan(null);
            fetchPlans(currentPage, pageSize);
          }}
        />
      )}
    </div>
  );
}




// Manage Institutions Modal
function ManageInstitutionsModal({
  plan,
  onClose,
}: {
  plan: ISubscriptionPlan;
  onClose: () => void;
}) {
  const [institutionMappings, setInstitutionMappings] = useState<Record<string, { isMapped: boolean; isVisible: boolean; isUsed: boolean }>>(
    Object.fromEntries(
      (plan.institutionSubscriptions ?? []).map((is: any) => [
        is.institutionId,
        {
          isMapped: true,
          isVisible: is.isVisible !== undefined ? is.isVisible : true,
          isUsed: false,
        },
      ])
    )
  );
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [saving, setSaving] = useState<string | null>(null);
  const [loadingMappings, setLoadingMappings] = useState(false);
  const [allInstitutions, setAllInstitutions] = useState<{ id: string; name: string }[]>([]);

  const fetchInstitutionsAndMappings = async () => {
    setLoadingMappings(true);
    try {
      const [instRes, mapRes] = await Promise.all([
        API_Instance.get(API_Constants.institutionsList, { params: { limit: -1, isVerified: true } }),
        API_Instance.get(`${API_Constants.subscriptionPlans}/${plan.id}/institutions`)
      ]);
      
      setAllInstitutions(instRes.data.data ?? []);

      const mapped = Object.fromEntries(
        (mapRes.data.data ?? []).map((sub: any) => [
          sub.institutionId,
          {
            isMapped: true,
            isVisible: sub.isVisible,
            isUsed: sub.isUsed ?? false,
          },
        ])
      );
      setInstitutionMappings(mapped);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoadingMappings(false);
    }
  };

  const fetchMappingsOnly = async () => {
    setLoadingMappings(true);
    try {
      const res = await API_Instance.get(`${API_Constants.subscriptionPlans}/${plan.id}/institutions`);
      const mapped = Object.fromEntries(
        (res.data.data ?? []).map((sub: any) => [
          sub.institutionId,
          {
            isMapped: true,
            isVisible: sub.isVisible,
            isUsed: sub.isUsed ?? false,
          },
        ])
      );
      setInstitutionMappings(mapped);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoadingMappings(false);
    }
  };

  useEffect(() => {
    fetchInstitutionsAndMappings();
  }, [plan.id]);

  const filtered = allInstitutions.filter((i) => {
    const matchesSearch = i.name.toLowerCase().includes(search.toLowerCase());
    if (plan.planType?.toLowerCase() === 'trial') {
      const mapping = institutionMappings[i.id];
      return matchesSearch && mapping && mapping.isMapped;
    }
    return matchesSearch;
  });

  const sorted = [...filtered].sort((a, b) => {
    const aMapped = institutionMappings[a.id]?.isMapped ? 1 : 0;
    const bMapped = institutionMappings[b.id]?.isMapped ? 1 : 0;
    if (aMapped !== bMapped) {
      return bMapped - aMapped;
    }
    return a.name.localeCompare(b.name);
  });

  const paginated = sorted.slice((page - 1) * pageSize, page * pageSize);

  const mappedIds = new Set(
    Object.entries(institutionMappings)
      .filter(([, value]) => value.isMapped)
      .map(([id]) => id)
  );

  const handleMapToggle = async (
    instId: string,
    currentlyMapped: boolean,
  ) => {
    setSaving(instId);
    try {
      if (currentlyMapped) {
        const newIds = [...mappedIds].filter((id) => id !== instId);
        await API_Instance.put(`${API_Constants.subscriptionPlans}/${plan.id}/institutions`, {
          institutionIds: newIds,
        });
        toast.success("Institution removed from plan");
      } else {
        const newIds = [...mappedIds, instId];
        await API_Instance.put(`${API_Constants.subscriptionPlans}/${plan.id}/institutions`, {
          institutionIds: newIds,
        });
        toast.success("Institution published to plan");
      }
      fetchMappingsOnly();
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setSaving(null);
    }
  };

  const handleVisibilityToggle = async (
    instId: string,
    isVisible: boolean,
  ) => {
    setSaving(instId);
    try {
      await API_Instance.patch(
        `${API_Constants.subscriptionPlans}/${plan.id}/institutions/${instId}`,
        { isVisible: isVisible }
      );
      toast.success(`This plan is now ${isVisible ? 'visible' : 'hidden'} for this institution`);
      fetchMappingsOnly();
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setSaving(null);
    }
  };

  const columns = [
    {
      title: "Institution Name",
      dataIndex: "name",
      key: "name",
      render: (name: string) => (
        <span className="font-semibold text-slate-800 text-sm">{name}</span>
      ),
    },
    {
      title: "Visibility",
      key: "visibility",
      render: (_: any, row: any) => {
        if (!row.mapping.isMapped) {
          return <span className="text-slate-400 text-xs italic">Not published</span>;
        }

        if (plan.planType?.toLowerCase() === 'trial') {
          return (
            <Tooltip title="Trial plan is always visible to verified institutions." placement="top">
              <div className="flex items-center gap-2 cursor-not-allowed">
                <Switch checked={true} size="small" disabled />
                <span className="text-xs font-medium text-blue-600">
                  Always Visible
                </span>
              </div>
            </Tooltip>
          );
        }

        const isVisible = row.mapping.isVisible;
        return (
          <Popconfirm
            title={isVisible ? "Hide this plan?" : "Make this plan visible?"}
            description={
              isVisible
                ? "This institution will no longer see this plan."
                : "This institution will be able to see this plan."
            }
            okText="Yes, Confirm"
            cancelText="Cancel"
            onConfirm={() => handleVisibilityToggle(row.id, !isVisible)}
            disabled={saving === row.id}
          >
            <div className="flex items-center gap-2 cursor-pointer">
              <Switch
                checked={isVisible}
                size="small"
                loading={saving === row.id}
              />
              <span className={`text-xs font-medium ${isVisible ? "text-blue-600" : "text-slate-400"}`}>
                {isVisible ? "Visible" : "Hidden"}
              </span>
            </div>
          </Popconfirm>
        );
      },
    },
    {
      title: "Action",
      key: "mapping",
      align: "right" as const,
      render: (_: any, row: any) => {
        const isMapped = row.mapping.isMapped;
        const isUsed = row.mapping.isUsed;

        if (plan.planType?.toLowerCase() === 'trial') {
          if (!isMapped) {
            return <span className="text-xs text-slate-300 italic">-</span>;
          }
          return (
            <Tooltip title="Verified institutions get the trial plan automatically and cannot be manually added or removed." placement="top">
              <span className="text-xs italic text-slate-400 cursor-not-allowed">Auto-assigned</span>
            </Tooltip>
          );
        }

        const actionLabel = isMapped ? "Remove" : "Publish Plan";
        const actionDisabled = isUsed && isMapped;

        const button = (
          <Popconfirm
            title={isMapped ? "Remove this institution from the plan?" : "Publish this plan to the institution?"}
            description={isMapped ? "This will remove the institution from this plan." : "This will publish this plan to the institution."}
            okText="Confirm"
            cancelText="Cancel"
            onConfirm={() => handleMapToggle(row.id, isMapped)}
          >
            <Button
              size="small"
              type={isMapped ? "default" : "primary"}
              danger={isMapped}
              loading={saving === row.id}
              disabled={actionDisabled || saving === row.id}
            >
              {actionLabel}
            </Button>
          </Popconfirm>
        );

        return actionDisabled ? (
          <Tooltip title="Already used this plan" placement="top">
            <span className="inline-block cursor-not-allowed">{button}</span>
          </Tooltip>
        ) : (
          button
        );
      },
    },
  ];

  return (
    <Modal
      isOpen
      onClose={onClose}
      title={`Manage Institutions - ${plan.planName}`}
      className="max-w-2xl"
    >
      <div className="space-y-4">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
          <p className="text-xs text-slate-500">
            Map institutions to this plan and control visibility separately.
          </p>
          <Input
            placeholder="Search institution..."
            prefix={<SearchIcon size={14} className="text-slate-400" />}
            allowClear
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(1); }}
            className="w-full sm:w-64 rounded-md"
          />
        </div>

        <Table
          columns={columns}
          dataSource={paginated.map((inst) => {
            const mapping = institutionMappings[inst.id] || {
              isMapped: false,
              isVisible: true,
              isUsed: false,
            };
            return {
              key: inst.id,
              ...inst,
              mapping,
            };
          })}
          rowKey="id"
          pagination={false}
          size="small"
          loading={loadingMappings}
          className="border border-slate-200 rounded-md overflow-hidden"
          locale={{
            emptyText: (
              <div className="py-8 text-center text-slate-400 text-xs">
                No institutions found.
              </div>
            ),
          }}
        />

        <div className="flex items-center justify-between pt-2 text-xs text-slate-500">
          <span>{filtered.length} institution{filtered.length !== 1 ? "s" : ""} total</span>
          <Pagination
            current={page}
            total={filtered.length}
            pageSize={pageSize}
            onChange={(p) => setPage(p)}
            showSizeChanger
            pageSizeOptions={["10", "20", "50", "100"]}
            onShowSizeChange={(_, size) => {
              setPageSize(size);
              setPage(1);
            }}
            size="small"
          />
        </div>
      </div>
    </Modal>
  );
}

// Plan Form Card
export function PlanFormCard({
  mode,
  initialValues,
  onSave,
  onCancel,
  loading,
}: PlanFormProps) {
  const [form] = Form.useForm();

  useEffect(() => {
    form.setFieldsValue(initialValues);
  }, [initialValues, form]);
  const planPrice = Form.useWatch("actualPrice", form);
  const discountPercentage = Form.useWatch("discountPercentage", form);
  const price = Number(planPrice);
  const discount = Number(discountPercentage);

  const finalPrice = Number(
    (price - (price * discount) / 100).toFixed(2)
  );

  return (
    <div className="space-y-6">
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
        onFinish={onSave}
        className="space-y-4"
      >
        {/*
        <Form.Item
          label="Subscription Account"
          name="subscriptionAccountId"
          rules={[{ required: true, message: "Subscription account is required" }]}
        >
          <Select
            className="rounded-lg w-full"
            disabled
            options={subscriptionAccounts.map((acc) => ({
              label: acc.name,
              value: acc.id,
            }))}
          />
        </Form.Item>
        */}

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {mode === "add" && (
            <Form.Item
              label="Plan Type (Slug)"
              name="planType"
              rules={[{ required: true, message: "Plan type is required" }]}
            >
              <Input
                placeholder="e.g. basic, premium, trial"
                className="rounded-lg"
              />
            </Form.Item>
          )}

          <Form.Item
            label="Plan Name"
            name="planName"
            rules={[{ required: true, message: "Plan name is required" }]}
          >
            <Input placeholder="e.g. Pro Monthly" className="rounded-lg" />
          </Form.Item>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Form.Item
            label="Actual Price (Rs.)"
            name="actualPrice"
            rules={[{ required: true, message: "Required" }]}
          >
            <InputNumber
              min={0}
              placeholder="0"
              className="w-full rounded-lg"
            />
          </Form.Item>

          <Form.Item
            label="Duration (Days)"
            name="duration"
            rules={[{ required: true, message: "Required" }]}
          >
            <InputNumber
              min={1}
              placeholder="30"
              className="w-full rounded-lg"
            />
          </Form.Item>

          <Form.Item
            label="Discount (%)"
            name="discountPercentage"
            rules={[{ required: true, message: "Required" }]}
          >
            <InputNumber
              min={0}
              max={100}
              placeholder="0"
              className="w-full rounded-lg"
            />
          </Form.Item>

          <Form.Item
            label="GST (%)"
            name="gstPercentage"
            rules={[{ required: true, message: "Required" }]}
          >
            <InputNumber
              min={0}
              max={100}
              placeholder="18"
              className="w-full rounded-lg"
            />
          </Form.Item>
        </div>
        <div className="text-blue-900 text-lg font-bold !mt-0">Plan final price: {finalPrice}</div>

        <Form.Item label="Description" name="description">
          <TextArea
            rows={2}
            placeholder="Brief description..."
            className="rounded-lg"
          />
        </Form.Item>

        <Form.List name="features">
          {(fields, { add, remove }) => (
            <div className="bg-gray-50 p-4 rounded-xl border border-gray-100">
              <p className="text-sm font-bold text-gray-700 mb-3">
                Features List:
              </p>

              <div className="space-y-2 max-h-48 overflow-y-auto pr-2 custom-scrollbar">
                {fields.map((field) => (
                  <div key={field.key} className="flex gap-2 items-center">
                    <Form.Item
                      {...field}
                      className="flex-1 mb-0"
                      rules={[{ required: true, message: "Required" }]}
                    >
                      <Input
                        placeholder="Type feature..."
                        className="rounded-lg shadow-sm"
                      />
                    </Form.Item>

                    <button
                      onClick={() => remove(field.name)}
                      className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                      type="button"
                    >
                      <X size={16} />
                    </button>
                  </div>
                ))}
              </div>

              <Button
                type="dashed"
                onClick={() => add("")}
                icon={<Plus size={14} />}
                className="mt-4 w-full rounded-lg border-blue-200 text-blue-600 hover:text-blue-700 hover:border-blue-300"
              >
                Add Feature
              </Button>
            </div>
          )}
        </Form.List>

        <div className="flex justify-end gap-3 pt-4 border-t border-gray-100">
          <Button onClick={onCancel} className="rounded-lg px-6 h-10">
            Cancel
          </Button>
          <Button
            type="primary"
            onClick={() => form.submit()}
            loading={loading}
            icon={<Save size={18} />}
            className="rounded-lg px-6 h-10 bg-blue-600 hover:bg-blue-700"
          >
            {mode === "add" ? "Create Plan" : "Update Plan"}
          </Button>
        </div>
      </Form>
    </div>
  );
}
