import { useForm, useWatch } from "react-hook-form";
import { motion } from "framer-motion";
import { Calendar, Target, FileText, ArrowLeft } from "lucide-react";
import {
  useLocation,
  useNavigate,
  useParams,
  useSearchParams,
} from "react-router-dom";
import { useEffect, useMemo } from "react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import {
  usePlan,
  usePlanMutations,
} from "@/performance-management/hooks/usePlans";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useAuth } from "@/shared/context/AuthContext";
import { useUnitContext } from "@/shared/context/UnitContext";
import { usePositions } from "@/user-management/hooks/usePosition";
import {
  usePlanYears,
  usePlanYearById,
} from "@/performance-management/hooks/usePlanYear";
import { Button } from "@/shared/common/ui/button";
import { Card, CardContent } from "@/shared/common/ui/card";
import { Alert, AlertDescription, AlertTitle } from "@/shared/common/ui/alert";
import { Info } from "lucide-react";
import { GenericForm } from "@/performance-management/utils/generic-form"; // Adjust import path as needed
import PlanType, {
  getDayList,
  getMonthList,
  getQuarterList,
  getWeekList,
  getPlanTypeOptions,
} from "@/performance-management/utils/plan-unit";
import {
  FormField,
  TimeFrame,
} from "@/performance-management/utils/shared-field-types";

export interface PlanFormValues {
  nameAm: string;
  nameEn: string;
  descriptionAm: string;
  descriptionEn: string;
  positionId: string;
  parentPlanId?: string;
  planType: PlanType;
  planYearId: string;
  // initialGoal: string;
  // expectedGoal: string;
  weight: string;
  month: string | number;
  week: string | number;
  day: string | number;
  quarter: string | number;
  timeframe: string | number;
  planFor?: string;
}

// Removed local TimeFrame enum definition

interface PlanFormProps {
  parentPlanId?: string;
  onSuccess?: () => void;
}

export default function PlanForm({
  parentPlanId: propParentId,
  onSuccess,
}: PlanFormProps = {}) {
  const navigate = useNavigate();
  const { t } = useTranslation();

  const {
    id,
    yearId: pathYearId,
    positionId,
    planId,
  } = useParams<{
    id: string;
    yearId?: string;
    positionId?: string;
    planId?: string;
  }>();
  console.log("positon id", positionId);
  const [searchParams] = useSearchParams();
  const urlParentId =
    searchParams.get("parentPlanId") || searchParams.get("parentId");
  const queryYearId = searchParams.get("yearId");
  // Get yearId from query params first (UUID), then fallback to path params
  const urlYearId = queryYearId || pathYearId;
  const location = useLocation();
  const planFor = location.state?.planFor as string | undefined;
  console.log("plan for in form", planFor);

  const parentId =
    propParentId || urlParentId || (planId === "root" ? undefined : planId);
  const { user } = useAuth();
  const localizedName = useLocalizedName();
  const isEdit = !!id;

  const organizationId =
    user?.employee?.length && user.employee.length > 0
      ? user.employee[0].organizationId
      : undefined;

  const unitContext = useUnitContext();
  const unitsQuery = unitContext?.getList(organizationId!, {
    take: 300,
    skip: 0,
  });
  const unitId = unitsQuery?.data?.data?.items?.[0]?.id ?? "";

  // Fetch the specific plan being edited
  const { data: planDetail } = usePlan(id ?? "");

  // Fetch parent plan data if parentId is present
  const { data: parentPlanDetail } = usePlan(parentId ?? "");

  const { usePositionListByUnitId } = usePositions();
  usePositionListByUnitId(unitId, { take: 100, skip: 0 });
  const { data: planYearsData } = usePlanYears(organizationId ?? "", {
    take: 100,
  });

  // Fetch specific plan year if yearId is provided in URL
  const { data: currentPlanYearData } = usePlanYearById(urlYearId ?? "");

  const { create: createMutation, update: updateMutation } = usePlanMutations();

  const normalizeTimeframe = (val: unknown): string => {
    if (!val) return TimeFrame.YEAR;
    const str = String(val).toLowerCase();
    if (str.includes("year")) return TimeFrame.YEAR;
    if (str.includes("quarter")) return TimeFrame.QUARTER;
    if (str.includes("month")) return TimeFrame.MONTH;
    if (str.includes("week")) return TimeFrame.WEEK;
    if (str.includes("day")) return TimeFrame.DAY;
    return TimeFrame.YEAR;
  };

  const initialPlanFormValues = useMemo(
    () => ({
      nameAm: planDetail?.data?.name?.am || "",
      nameEn: planDetail?.data?.name?.en || "",
      descriptionAm: planDetail?.data?.description?.am || "",
      descriptionEn: planDetail?.data?.description?.en || "",
      positionId: positionId || "",
      parentPlanId:
        planDetail?.data?.parentPlanId || parentId || planId || undefined,
      planType: planDetail?.data?.planType || "percent",
      planYearId: planDetail?.data?.planYearId || urlYearId || "",
      // initialGoal: planDetail?.data?.initialGoal?.toString() || "",
      // expectedGoal: planDetail?.data?.expectedGoal?.toString() || "",
      weight: planDetail?.data?.weight?.toString() || "",
      month: planDetail?.data?.month?.toString() || "0",
      week: planDetail?.data?.week?.toString() || "0",
      day: planDetail?.data?.day?.toString() || "0",
      quarter: planDetail?.data?.quarter?.toString() || "0",
      timeframe: (() => {
        const rawTimeframe = planDetail?.data?.timeframe;
        if (rawTimeframe) return normalizeTimeframe(rawTimeframe);

        // Fallback for sub-plan creation when parent data is missing but parentId is present
        if (!parentId || !parentPlanDetail?.data) {
          return parentId ? TimeFrame.QUARTER : TimeFrame.YEAR;
        }

        const pt = normalizeTimeframe(parentPlanDetail.data.timeframe);
        if (pt === TimeFrame.YEAR) return TimeFrame.QUARTER;
        if (pt === TimeFrame.QUARTER) return TimeFrame.QUARTER;
        if (pt === TimeFrame.MONTH) return TimeFrame.WEEK;
        if (pt === TimeFrame.WEEK) return TimeFrame.DAY;
        return TimeFrame.YEAR;
      })(),
    }),
    [
      planDetail?.data,
      positionId,
      parentId,
      planId,
      urlYearId,
      parentPlanDetail?.data,
    ],
  );

  const form = useForm<PlanFormValues>({
    defaultValues: initialPlanFormValues,
    values: isEdit || !!parentId ? initialPlanFormValues : undefined,
  });

  const watchedParentPlanId = useWatch({
    control: form.control,
    name: "parentPlanId",
  });

  const { data: watchedParentPlanDetail } = usePlan(
    watchedParentPlanId && watchedParentPlanId !== "root"
      ? watchedParentPlanId
      : "",
  );

  const effectiveParentDetail = watchedParentPlanDetail || parentPlanDetail;

  const planOptions =
    planDetail?.data?.items?.map(
      (plan: { id: string; name: { am: string; en: string } }) => ({
        label: localizedName(plan.name),
        value: plan.id,
        icon: FileText,
      }),
    ) || [];

  // Add parent plan to options if it exists and isn't already in the list
  if (parentId && parentPlanDetail?.data) {
    const parentPlanExists = planOptions.some(
      (option: { label: string; value: string }) => option.value === parentId,
    );
    if (!parentPlanExists) {
      planOptions.unshift({
        label: localizedName(parentPlanDetail.data.name),
        value: parentId,
        icon: FileText,
      });
    }
  }

  // If yearId is in URL, show only that year; otherwise show all years
  const planYearOptions =
    urlYearId && currentPlanYearData?.data
      ? [
          {
            value: currentPlanYearData.data.id,
            label: `${currentPlanYearData.data.year}`,
            icon: Calendar,
          },
        ]
      : planYearsData?.data?.items?.map(
          (year: { id: string; year: number }) => ({
            value: year.id,
            label: `${year.year}`,
            icon: Calendar,
          }),
        ) || [];

  const planTypeOptions = useMemo(() => getPlanTypeOptions(), []);

  const timeframeOptions = useMemo(() => {
    const parent = effectiveParentDetail?.data;

    // If no parent plan, only allow Yearly
    if (!parentId && !parent && !watchedParentPlanId) {
      return [
        {
          value: TimeFrame.YEAR,
          label: t("plans.Yearly"),
        },
      ];
    }

    const parentTimeframe = normalizeTimeframe(parent?.timeframe);

    // Based on parent timeframe, allow the next level down
    switch (parentTimeframe) {
      case TimeFrame.YEAR:
        return [
          {
            value: TimeFrame.YEAR,
            label: t("plans.Yearly", "Yearly"),
          },
          {
            value: TimeFrame.QUARTER,
            label: t("plans.Quarterly"),
          },
        ];

      case TimeFrame.QUARTER:
        return [
          {
            value: TimeFrame.QUARTER,
            label: t("plans.Quarterly", "Quarterly"),
          },
        ];

      case TimeFrame.MONTH:
        return [
          {
            value: TimeFrame.WEEK,
            label: t("plans.Weekly"),
          },
        ];

      case TimeFrame.WEEK:
        return [
          {
            value: TimeFrame.DAY,
            label: t("plans.Daily"),
          },
        ];

      default:
        // Fallback to yearly if parent timeframe is unknown
        return [
          {
            value: TimeFrame.YEAR,
            label: t("plans.Yearly"),
          },
        ];
    }
  }, [parentId, effectiveParentDetail?.data, watchedParentPlanId, t]);

  // Memoize the list options to ensure they update when language changes
  const monthListOptions = useMemo(() => getMonthList(t), [t]);
  const weekListOptions = useMemo(() => getWeekList(t), [t]);
  const dayListOptions = useMemo(() => getDayList(t), [t]);
  const quarterListOptions = useMemo(() => getQuarterList(t), [t]);

  const watchedTimeframe = useWatch({
    control: form.control,
    name: "timeframe",
  });

  // Reset hidden fields when timeframe changes, but preserve context for "drill-down" scenarios
  useEffect(() => {
    if (watchedTimeframe === TimeFrame.QUARTER) {
      form.setValue("month", "0");
      form.setValue("week", "0");
      form.setValue("day", "0");
    } else if (watchedTimeframe === TimeFrame.MONTH) {
      form.setValue("week", "0");
      form.setValue("day", "0");
    } else if (watchedTimeframe === TimeFrame.WEEK) {
      form.setValue("day", "0");
    } else if (watchedTimeframe === TimeFrame.YEAR) {
      form.setValue("quarter", "0");
      form.setValue("month", "0");
      form.setValue("week", "0");
      form.setValue("day", "0");
    }
  }, [watchedTimeframe, form]);

  // Auto-select timeframe if there's only one option
  useEffect(() => {
    if (timeframeOptions.length === 1) {
      const currentVal = form.getValues("timeframe");
      if (currentVal !== timeframeOptions[0].value) {
        form.setValue("timeframe", timeframeOptions[0].value, {
          shouldValidate: true,
          shouldDirty: true,
        });
      }
    }
  }, [timeframeOptions, form]);

  useEffect(() => {
    const current = form.getValues("timeframe");

    const isValid = timeframeOptions.some((opt) => opt.value === current);

    if (!isValid && timeframeOptions.length > 0) {
      form.setValue("timeframe", timeframeOptions[0].value, {
        shouldValidate: true,
        shouldDirty: true,
      });
    }
  }, [timeframeOptions, form]);

  // Inherit timeframe context from parent plan
  useEffect(() => {
    if (parentId && parentPlanDetail?.data && !isEdit) {
      const parent = parentPlanDetail.data;

      // Inherit Plan Year
      if (parent.planYearId) {
        form.setValue("planYearId", parent.planYearId);
      }

      // Determine Child Timeframe and Context based on Parent
      switch (parent.timeframe) {
        case TimeFrame.YEAR:
          form.setValue("timeframe", TimeFrame.QUARTER);
          break;

        case TimeFrame.QUARTER:
          form.setValue("timeframe", TimeFrame.QUARTER);
          if (parent.quarter) {
            form.setValue("quarter", parent.quarter.toString());
          }
          break;

        case TimeFrame.MONTH:
          form.setValue("timeframe", TimeFrame.WEEK);
          if (parent.quarter) {
            form.setValue("quarter", parent.quarter.toString());
          }
          if (parent.month) {
            form.setValue("month", parent.month.toString());
          }
          break;

        case TimeFrame.WEEK:
          form.setValue("timeframe", TimeFrame.DAY);
          if (parent.quarter) {
            form.setValue("quarter", parent.quarter.toString());
          }
          if (parent.month) {
            form.setValue("month", parent.month.toString());
          }
          if (parent.week) {
            form.setValue("week", parent.week.toString());
          }
          break;

        default:
          break;
      }
    }
  }, [parentId, parentPlanDetail, isEdit, form]);

  // Auto-populate plan year when yearId is in URL or when plan year data loads
  useEffect(() => {
    // If yearId is in URL, use the current plan year data
    if (urlYearId && currentPlanYearData?.data) {
      form.setValue("planYearId", currentPlanYearData.data.id);
    } else if (planYearsData?.data?.items) {
      const currentVal = form.getValues("planYearId");
      // If current value is a year number (e.g. "2022"), try to find the UUID
      const matched = planYearsData.data.items.find(
        (y: { id: string; year: number }) =>
          y.year.toString() === currentVal || y.id === currentVal,
      );

      if (matched && matched.id !== currentVal) {
        form.setValue("planYearId", matched.id);
      }
    }
  }, [form, planYearsData, urlYearId, currentPlanYearData]);

  // Helper function to convert TimeFrame enum to number
  // (Removed - not currently used)

  const handleSubmit = (values: PlanFormValues) => {
    // Check if plan is already accepted (case-insensitive)
    const planStatus = planDetail?.data?.status?.toLowerCase();
    console.log("Plan status:", planStatus, "Plan detail:", planDetail?.data);

    if (isEdit && planStatus === "accepted") {
      toast.error(t("plans.planAlreadyAccepted", "Plan is already accepted"), {
        description: t(
          "plans.cannotEditAcceptedPlan",
          "You cannot edit a plan that has already been accepted",
        ),
      });
      return;
    }

    // Create base DTO without timeframe-specific fields
    const baseDto = {
      id: isEdit ? id : undefined,
      name: {
        am: values.nameAm,
        en: values.nameEn,
      },
      description: {
        am: values.descriptionAm,
        en: values.descriptionEn,
      },
      positionId: positionId || values.positionId || undefined,
      parentPlanId:
        planId === "root" || !values.parentPlanId
          ? undefined
          : (values.parentPlanId as string),
      planType: values.planType || PlanType.PERCENTAGE,
      planYearId: values.planYearId,
      timeframe: values.timeframe as string,
      // initialGoal: Number(values.initialGoal),
      // expectedGoal: Number(values.expectedGoal),
      weight: Number(values.weight),
      planFor: planFor || values.planFor || undefined,
    };

    // Add timeframe-specific fields based on the selected timeframe
    let timeframeSpecificFields = {};

    switch (values.timeframe) {
      case TimeFrame.YEAR:
        // Yearly plans don't need quarter, month, week, day
        timeframeSpecificFields = {
          quarter: undefined,
          month: undefined,
          week: undefined,
          day: undefined,
        };
        break;

      case TimeFrame.QUARTER:
        // Quarterly plans need quarter only
        timeframeSpecificFields = {
          quarter: Number(values.quarter),
          month: undefined,
          week: undefined,
          day: undefined,
        };
        break;

      case TimeFrame.MONTH:
        // Monthly plans need quarter and month
        timeframeSpecificFields = {
          quarter: undefined,
          month: Number(values.month),
          week: undefined,
          day: undefined,
        };
        break;

      case TimeFrame.WEEK:
        // Weekly plans need quarter, month, and week
        timeframeSpecificFields = {
          quarter: undefined,
          month: undefined,
          week: Number(values.week),
          day: undefined,
        };
        break;

      case TimeFrame.DAY:
        // Daily plans need all timeframe fields
        timeframeSpecificFields = {
          quarter: undefined,
          month: undefined,
          week: undefined,
          day: Number(values.day),
        };
        break;

      default:
        // Fallback - set all to 0
        timeframeSpecificFields = {
          quarter: undefined,
          month: undefined,
          week: undefined,
          day: undefined,
        };
    }

    // Combine base DTO with timeframe-specific fields
    const dto = {
      ...baseDto,
      ...timeframeSpecificFields,
    };

    const mutation = isEdit ? updateMutation : createMutation;

    mutation.mutate(dto, {
      onSuccess: () => {
        toast.success(
          isEdit
            ? t("plans.planUpdatedSuccess", "Plan updated successfully!")
            : t("plans.planCreatedSuccess", "Plan created successfully!"),
          {
            description: `"${values.nameEn}" ${t(
              "common.hasBeenText",
              "has been",
            )} ${
              isEdit
                ? t("common.updated", "updated")
                : t("common.created", "created")
            }.`,
          },
        );
        onSuccess?.();
        if (!isEdit) {
          // After creating a plan, navigate to the plans-table view for the
          // appropriate year / position / parent plan. Use path params first
          // (if the form was opened via a route containing them), otherwise
          // fall back to the submitted form values.
          const targetYear = urlYearId || values.planYearId || pathYearId;
          const targetPosition = positionId || values.positionId;
          const targetPlan =
            planId || (values.parentPlanId as string) || parentId;

          if (targetYear && targetPosition && targetPlan) {
            navigate(
              `/performance-management/${targetYear}/plans-table/${targetPosition}/${targetPlan}`,
            );
          } else if (targetYear && targetPosition) {
            navigate(
              `/performance-management/${targetYear}/plans-table/${targetPosition}`,
            );
          } else if (targetYear) {
            navigate(`/performance-management/${targetYear}/plans`);
          } else {
            navigate(`/performance-management`);
          }
        }
      },
    });
  };

  // Define form fields with sections
  const planFormFields: FormField<PlanFormValues>[] = [
    // Basic Information Section
    {
      name: "nameAm",
      label: t("plans.nameAmharic", "Name (Amharic)"),
      type: "text",
      placeholder: t("plans.planNameAmharic", "የዕቅድ ስም አማርኛ"),
      required: true,
      icon: FileText,
      section: t("plans.basicInformation", "Basic Information"),
      colSpan: 6,
    },
    {
      name: "nameEn",
      label: t("plans.nameEnglish", "Name (English)"),
      type: "text",
      placeholder: t("plans.planNameEnglish", "Plan Name in English"),
      required: true,
      icon: FileText,
      section: t("plans.basicInformation", "Basic Information"),
      colSpan: 6,
    },
    {
      name: "descriptionEn",
      label: t("plans.descriptionEnglish", "Description (English)"),
      type: "textarea",
      placeholder: t(
        "plans.describePlanEnglish",
        "Describe the plan in English...",
      ),
      required: true,
      icon: FileText,
      section: t("plans.basicInformation", "Basic Information"),
      colSpan: 12,
    },
    {
      name: "descriptionAm",
      label: t("plans.descriptionAmharic", "Description (Amharic)"),
      type: "textarea",
      placeholder: t("plans.describePlanAmharic", "ዕቅዱን በአማርኛ ይግለጹ..."),
      required: true,
      icon: FileText,
      section: t("plans.basicInformation", "Basic Information"),
      colSpan: 12,
    },

    // Organization Section
    {
      name: "planYearId",
      label: t("plans.planYear", "Plan Year"),
      type: "select",
      options: planYearOptions,
      required: true,
      icon: Calendar,
      section: t("plans.organization", "Organization"),
      colSpan: 4,
      disabled: !!urlYearId, // Disable if yearId is in URL params
    },
    {
      name: "timeframe",
      label: t("plans.timeFrame", "Time Frame"),
      type: "select",
      options: timeframeOptions,
      placeholder: t("plans.enterTimeFrame", "Enter time frame"),
      required: true,
      disabled: timeframeOptions.length === 1,
      icon: Calendar,
      section: t("plans.organization", "Organization"),
      colSpan: 4,
    },
    // {
    //   name: "initialGoal",
    //   label: t("plans.initialGoal", "Initial Goal"),
    //   type: "number",
    //   required: true,
    //   icon: Target,
    //   section: t("plans.organization", "Organization"),
    //   colSpan: 2,
    // },
    // {
    //   name: "expectedGoal",
    //   label: t("plans.expectedGoal", "Expected Goal"),
    //   type: "number",
    //   placeholder: t("plans.enterExpectedGoal", "Enter expected goal"),
    //   icon: Users,
    //   section: t("plans.organization", "Organization"),
    //   colSpan: 2,
    // },

    // Plan Details Section
    {
      name: "parentPlanId",
      label: t("plans.parentPlan", "Parent Plan"),
      type: "select",
      options: planOptions,
      icon: FileText,
      section: t("plans.planDetails", "Plan Details"),
      disabled: !!parentId || !!planId,
      colSpan: 4,
      defaultValue: parentId || planId || undefined,
    },
    {
      name: "weight",
      label: t("plans.weight", "Weight"),
      type: "number",
      placeholder: t("plans.enterWeight", "Enter weight"),
      icon: Target,
      section: t("plans.planDetails", "Plan Details"),
      colSpan: 2,
    },
    {
      name: "month",
      label: t("plans.month", "Month"),
      type: "select",
      placeholder: t("plans.enterMonth", "Enter month"),
      icon: Calendar,
      section: t("plans.planDetails", "Plan Details"),
      hidden:
        watchedTimeframe !== TimeFrame.MONTH &&
        (!form.getValues("month") || form.getValues("month") === "0"),
      colSpan: 3,
      options: monthListOptions,
      disabled: parentPlanDetail?.data?.timeframe === TimeFrame.MONTH,
    },
    {
      name: "week",
      label: t("plans.week", "Week"),
      type: "select",
      placeholder: t("plans.enterWeek", "Enter week"),
      icon: Calendar,
      section: t("plans.planDetails", "Plan Details"),
      hidden:
        watchedTimeframe !== TimeFrame.WEEK &&
        (!form.getValues("week") || form.getValues("week") === "0"),
      colSpan: 4,
      options: weekListOptions,
      disabled: parentPlanDetail?.data?.timeframe === TimeFrame.WEEK,
    },
    {
      name: "day",
      label: t("plans.day", "Day"),
      type: "select",
      placeholder: t("plans.enterDay", "Enter day"),
      icon: Calendar,
      section: t("plans.planDetails", "Plan Details"),
      hidden: watchedTimeframe !== TimeFrame.DAY,
      colSpan: 4,
      options: dayListOptions,
      disabled: parentPlanDetail?.data?.timeframe === TimeFrame.DAY,
    },
    {
      name: "quarter",
      label: t("plans.quarter", "Quarter"),
      type: "select",
      placeholder: t("plans.enterQuarter", "Enter quarter"),
      icon: Calendar,
      section: t("plans.planDetails", "Plan Details"),
      hidden:
        watchedTimeframe !== TimeFrame.QUARTER &&
        (!form.getValues("quarter") || form.getValues("quarter") === "0"),
      colSpan: 4,
      options: quarterListOptions,
      disabled: parentPlanDetail?.data?.timeframe === TimeFrame.QUARTER,
    },
    {
      name: "planType",
      label: t("plans.planType", "Plan Type"),
      type: "select",
      options: planTypeOptions,
      icon: FileText,
      section: t("plans.planDetails", "Plan Details"),
      colSpan: 4,
    },
  ];

  // Filter fields based on timeframe
  const filteredFields = planFormFields.filter((field) => {
    if (field.hidden) return false;
    return true;
  });

  const handleCancel = () => {
    navigate(-1);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-4 sm:p-6">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex items-center justify-between mb-8"
        >
          <div className="flex items-center space-x-4">
            <Button
              variant="outline"
              size="sm"
              onClick={() => navigate(-1)}
              className="border-gray-300 text-gray-700 hover:bg-gray-50"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              {t("common.back", "Back")}
            </Button>
            <div>
              <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-transparent">
                {isEdit
                  ? t("plans.editPlan", "Edit Plan")
                  : t("plans.createNewPlan", "Create New Plan")}
              </h1>
            </div>
          </div>
        </motion.div>
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
        >
          <Card className="bg-white/80 backdrop-blur-sm border-0 shadow-xl overflow-hidden">
            <CardContent className="p-6">
              {/* Plan Already Accepted Alert */}
              {isEdit &&
                planDetail?.data?.status?.toLowerCase() === "accepted" && (
                  <Alert className="mb-6 bg-red-50/80 border-red-200/50 backdrop-blur-sm">
                    <Info className="h-4 w-4 text-red-600" />
                    <AlertTitle className="text-red-900 font-semibold">
                      {t("plans.planAlreadyAccepted", "Plan Already Accepted")}
                    </AlertTitle>
                    <AlertDescription className="text-red-700">
                      {t(
                        "plans.cannotEditAcceptedPlan",
                        "This plan has already been accepted and cannot be edited. Please contact your administrator if you need to make changes.",
                      )}
                    </AlertDescription>
                  </Alert>
                )}

              {/* Parent Plan Info Alert */}
              {parentId && parentPlanDetail?.data && (
                <Alert className="mb-6 bg-blue-50/80 border-blue-200/50 backdrop-blur-sm">
                  <Info className="h-4 w-4 text-blue-600" />
                  <AlertTitle className="text-blue-900 font-semibold">
                    {t("plans.creatingSubPlan", "Creating Sub-Plan")}
                  </AlertTitle>
                  <AlertDescription className="text-blue-700">
                    {t(
                      "plans.subPlanDescription",
                      "This plan will be created as a sub-plan under:",
                    )}{" "}
                    <strong className="text-blue-900">
                      {localizedName(parentPlanDetail.data.name)}
                    </strong>
                  </AlertDescription>
                </Alert>
              )}

              <GenericForm
                form={form}
                fields={filteredFields.map((field) => ({
                  ...field,
                  disabled:
                    field.disabled ||
                    (isEdit &&
                      planDetail?.data?.status?.toLowerCase() === "accepted"),
                }))}
                onSubmit={handleSubmit}
                onCancel={handleCancel}
                isSubmitting={
                  createMutation.isPending || updateMutation.isPending
                }
                submitButtonText={
                  isEdit
                    ? t("plans.updatePlan", "Update Plan")
                    : t("plans.createPlan", "Create Plan")
                }
                cancelButtonText={t("common.cancel", "Cancel")}
                successMessage={
                  isEdit
                    ? t(
                        "plans.planUpdatedSuccessfully",
                        "Plan updated successfully!",
                      )
                    : t(
                        "plans.planCreatedSuccessfully",
                        "Plan created successfully!",
                      )
                }
                errorMessage={
                  isEdit
                    ? t("plans.failedToUpdatePlan", "Failed to update plan")
                    : t("plans.failedToCreatePlan", "Failed to create plan")
                }
              />
            </CardContent>
          </Card>
        </motion.div>
      </div>
    </div>
  );
}
