import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import DateMeasurementUnit from "@/performance-management/utils/data-measurement-unit";
import { GenericForm } from "@/performance-management/utils/generic-form";
import { FormField } from "@/performance-management/utils/shared-field-types";

import {
  useService,
  useServiceMutations,
  useServiceList,
} from "@/performance-management/hooks/useServiceHook";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useServiceCategoryList } from "@/performance-management/hooks/useServiceCategory";
import { useAuth } from "@/shared/context/AuthContext";
import { useState } from "react";

// Validation schema factory
const createServiceSchema = (t: (key: string) => string) =>
  z.object({
    slug: z.string().optional(),
    prefix: z.string().optional(),
    nameAm: z
      .string()
      .min(1, t("services.validation.nameAmRequired"))
      .max(100, t("services.validation.nameMaxLength")),
    nameEn: z
      .string()
      .min(1, t("services.validation.nameEnRequired"))
      .max(100, t("services.validation.nameMaxLength")),
    descriptionAm: z
      .string()
      .min(1, t("services.validation.descriptionAmRequired"))
      .max(500, t("services.validation.descriptionMaxLength")),
    descriptionEn: z
      .string()
      .min(1, t("services.validation.descriptionEnRequired"))
      .max(500, t("services.validation.descriptionMaxLength")),
    organizationId: z
      .string()
      .min(1, t("services.validation.organizationRequired")),
    serviceCategoryId: z
      .string()
      .min(1, t("services.validation.categoryRequired")),
    parentServiceId: z.string().optional(),
    estimatedTime: z
      .coerce.number()
      .min(1, t("services.validation.estimatedTimeMin"))
      .max(1440, t("services.validation.estimatedTimeMax")), // Max 24 hours in minutes
    estimatedTimeUnit: z.nativeEnum(DateMeasurementUnit),
  });

interface ServiceFormValues {
  slug?: string;
  prefix?: string;
  nameAm: string;
  nameEn: string;
  descriptionAm: string;
  descriptionEn: string;
  organizationId: string;
  serviceCategoryId: string;
  parentServiceId?: string;
  estimatedTime: number;
  estimatedTimeUnit: DateMeasurementUnit;
}

export default function ServiceForm() {
  const { id } = useParams<{ id: string }>(); // Get id from URL
  const isEdit = !!id;
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const { user } = useAuth();
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>("");

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

  // Fetch service categories
  const { data: serviceCategoriesResponse } =
    useServiceCategoryList(organizationId);

  // Fetch parent services based on selected category
  const { data: parentServicesResponse } = useServiceList(
    organizationId,
    selectedCategoryId || undefined
  );

  // Debug: Log the response to see its structure
  console.log("Service Categories Response:", serviceCategoriesResponse);
  console.log(
    "serviceCategoriesResponse?.data:",
    serviceCategoriesResponse?.data
  );

  // Extract service categories from response - handle different response structures
  let serviceCategories = [];
  if (serviceCategoriesResponse?.data) {
    // Try different possible structures
    if (Array.isArray(serviceCategoriesResponse.data)) {
      serviceCategories = serviceCategoriesResponse.data;
    } else if (serviceCategoriesResponse.data.data) {
      serviceCategories = Array.isArray(serviceCategoriesResponse.data.data)
        ? serviceCategoriesResponse.data.data
        : [];
    } else if (serviceCategoriesResponse.data.items) {
      serviceCategories = Array.isArray(serviceCategoriesResponse.data.items)
        ? serviceCategoriesResponse.data.items
        : [];
    }
  }

  console.log("Extracted Service Categories:", serviceCategories);

  // Extract parent services
  let parentServices = [];
  if (parentServicesResponse?.data) {
    if (Array.isArray(parentServicesResponse.data)) {
      parentServices = parentServicesResponse.data;
    } else if (parentServicesResponse.data.data) {
      parentServices = Array.isArray(parentServicesResponse.data.data)
        ? parentServicesResponse.data.data
        : [];
    } else if (parentServicesResponse.data.items) {
      parentServices = Array.isArray(parentServicesResponse.data.items)
        ? parentServicesResponse.data.items
        : [];
    }
  }

  // Fetch single service (for edit)
  const { data: serviceDetail } = useService(id ?? "");

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

  const initialValues: ServiceFormValues = {
    slug: serviceDetail?.data?.slug || "",
    prefix: serviceDetail?.data?.prefix || "",
    nameAm: serviceDetail?.data?.name?.am || "",
    nameEn: serviceDetail?.data?.name?.en || "",
    descriptionAm: serviceDetail?.data?.description?.am || "",
    descriptionEn: serviceDetail?.data?.description?.en || "",
    organizationId: serviceDetail?.data?.organizationId || organizationId,
    serviceCategoryId: serviceDetail?.data?.serviceCategoryId || "",
    parentServiceId: serviceDetail?.data?.parentServiceId || undefined,
    estimatedTime: serviceDetail?.data?.estimatedTime || 0,
    estimatedTimeUnit:
      serviceDetail?.data?.estimatedTimeUnit || DateMeasurementUnit.MINUTES,
  };

  // Update selected category when service detail loads or form changes
  if (serviceDetail?.data?.serviceCategoryId && !selectedCategoryId) {
    setSelectedCategoryId(serviceDetail.data.serviceCategoryId);
  }

  const fields: FormField<ServiceFormValues>[] = [
    {
      name: "slug",
      label: t("services.slug", "Slug"),
      type: "text",
      placeholder: t("services.enterSlug", "Enter slug"),
      required: false,
    },
    {
      name: "prefix",
      label: t("services.prefix", "Prefix"),
      type: "text",
      placeholder: t("services.enterPrefix", "Enter prefix"),
      required: false,
    },
    {
      name: "serviceCategoryId",
      label: t("services.serviceCategoryField", "Service Category"),
      type: "select",
      placeholder: t(
        "services.selectServiceCategory",
        "Select Service Category"
      ),
      required: true,

      options: (() => {
        const options = Array.isArray(serviceCategories)
          ? serviceCategories.map((category) => {
              console.log("Processing category:", category);
              return {
                value: category.id,
                label: localizedName(category.name),
              };
            })
          : [];
        console.log("Generated dropdown options:", options);
        return options;
      })(),
      onChange: (value: string) => {
        setSelectedCategoryId(value);
        form.setValue("parentServiceId", undefined); // Reset parent service when category changes
      },
    },
    {
      name: "parentServiceId",
      label: t("services.parentService", "Parent Service (Optional)"),
      type: "select",
      placeholder: t(
        "services.parentServiceOptional",
        "Parent Service (Optional)"
      ),
      required: false,
      options: parentServices.map(
        (service: { id: string; name: { en: string; am: string } }) => ({
          value: service.id,
          label: localizedName(service.name),
        })
      ),
    },
    {
      name: "nameAm",
      label: t("services.nameAm", "Name (Amharic)"),
      type: "text",
      placeholder: t("services.nameAmPlaceholder", "Enter Amharic name"),
      required: true,
    },
    {
      name: "nameEn",
      label: t("services.nameEn", "Name (English)"),
      type: "text",
      placeholder: t("services.nameEnPlaceholder", "Enter English name"),
      required: true,
    },
    {
      name: "descriptionAm",
      label: t("services.descriptionAm", "Description (Amharic)"),
      type: "textarea",
      placeholder: t(
        "services.descriptionAmPlaceholder",
        "Enter Amharic description"
      ),
      required: true,
    },
    {
      name: "descriptionEn",
      label: t("services.descriptionEn", "Description (English)"),
      type: "textarea",
      placeholder: t(
        "services.descriptionEnPlaceholder",
        "Enter English description"
      ),
      required: true,
    },
    {
      name: "estimatedTime",
      label: t("services.estimatedTime", "Estimated Time"),
      type: "number",
      placeholder: t("services.enterEstimatedTime", "Enter estimated time"),
    },
    {
      name: "estimatedTimeUnit",
      label: t("services.timeUnit", "Time Unit"),
      type: "select",
      options: Object.values(DateMeasurementUnit).map((unit) => ({
        value: unit,
        label: t(`services.timeUnits.${unit.toLowerCase()}`, unit),
      })),
    },
  ];

  const form = useForm<ServiceFormValues>({
    resolver: zodResolver(createServiceSchema(t)),
    defaultValues: initialValues,
    values: initialValues, // Important for Edit Mode
  });

  const handleSubmit = (values: ServiceFormValues) => {
    const dto = {
      id: isEdit ? id : undefined, // Include id for updates
      slug: values.slug || "",
      prefix: values.prefix || "",
      name: {
        am: values.nameAm,
        en: values.nameEn,
      },
      description: {
        am: values.descriptionAm,
        en: values.descriptionEn,
      },
      organizationId: values.organizationId,
      serviceCategoryId: values.serviceCategoryId,
      parentServiceId: values.parentServiceId || undefined,
      estimatedTime: Number(values.estimatedTime) || 0,
      estimatedTimeUnit: values.estimatedTimeUnit,
    };

    if (isEdit) {
      updateMutation.mutate(dto);
    } else {
      createMutation.mutate(dto);
    }
  };

  return (
    <GenericForm<ServiceFormValues>
      form={form}
      fields={fields}
      onSubmit={handleSubmit}
      submitButtonText={
        isEdit
          ? t("services.updateService", "Update Service")
          : t("services.createService", "Create Service")
      }
      title={
        isEdit
          ? t("services.editTitle", "Edit Service")
          : t("services.createTitle", "Create Service")
      }
      description={
        isEdit
          ? t("services.editDescription", "Update the service information")
          : t(
              "services.createDescription",
              "Add a new service to your organization"
            )
      }
      successMessage={
        isEdit
          ? t("services.updateSuccess", "Service updated successfully")
          : t("services.createSuccess", "Service created successfully")
      }
      errorMessage={
        isEdit
          ? t("services.updateError", "Failed to update service")
          : t("services.createError", "Failed to create service")
      }
    />
  );
}
