import { useState } from "react";
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "../../ui/form";
import EthiopianDatePickerModal, {
  convertEthiopianToGregorian,
} from "./AmharicDatePicker";
import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";
import { Button } from "../../ui/button";
import { Input } from "../../ui/input";
import { cn } from "@/shared/lib/utils";
import { format } from "date-fns";
import { CalendarIcon, Clock } from "lucide-react";
import { Calendar } from "../../ui/calendar";
import { useTranslation } from "react-i18next";
import $ from "@/shared/common/jquery-global";
import {
  formatEthiopianClockTime,
  utcToEthiopian,
} from "@/shared/common/utils/ethiopianTimeZone";

interface DateTimeFieldProps {
  name: "startDate" | "endDate";
  label: string;
  control: any;
  isEthiopian: boolean;
  isEditing: boolean;
  fieldValue?: Date | null;
}

interface EthiopianCalendarFormatter {
  fromJSDate: (jsDate: Date) => unknown;
  formatDate: (
    format: string,
    date: unknown,
    settings?: { localNumbers?: boolean },
  ) => string;
}

const DateTimeField: React.FC<DateTimeFieldProps> = ({
  name,
  label,
  control,
  isEthiopian,
  isEditing,
  fieldValue,
}) => {
  const [ethiopianDisplay, setEthiopianDisplay] = useState<string | null>("");
  const [showTimeInput, setShowTimeInput] = useState(false);
  const { t } = useTranslation();

  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => {
        const handleEthiopianChange = (ethiopianDate: string) => {
          setEthiopianDisplay(ethiopianDate);
          const gregorianDate = convertEthiopianToGregorian(ethiopianDate);
          field.onChange(gregorianDate);
        };

        const handleTimeChange = (hours: string, minutes: string) => {
          if (field.value) {
            const date = new Date(field.value);
            date.setHours(parseInt(hours) || 0, parseInt(minutes) || 0, 0, 0);
            field.onChange(date);
          }
        };

        const getTimeString = () => {
          if (!field.value) return "";
          const date = new Date(field.value);
          const hours = String(date.getHours()).padStart(2, "0");
          const minutes = String(date.getMinutes()).padStart(2, "0");
          return `${hours}:${minutes}`;
        };

        const getDateTimeDisplay = () => {
          if (!field.value) return t("delegation.pickDate");
          const date = new Date(field.value);
          if (Number.isNaN(date.getTime())) return t("delegation.pickDate");
          const timeStr = isEthiopian
            ? formatEthiopianClockTime(date)
            : getTimeString();

          const dateStr = (() => {
            if (!isEthiopian) return format(date, "PPP");
            if (ethiopianDisplay) return ethiopianDisplay.split(" ")[0];

            try {
              const ethiopianCalendar = $.calendars.instance(
                "ethiopian",
                "am",
              ) as unknown as EthiopianCalendarFormatter;
              const ethiopianDate = ethiopianCalendar.fromJSDate(
                utcToEthiopian(date),
              );
              return ethiopianCalendar.formatDate(
                "yyyy-mm-dd",
                ethiopianDate,
                { localNumbers: true },
              );
            } catch {
              return format(utcToEthiopian(date), "yyyy-MM-dd");
            }
          })();
          return `${dateStr} ${timeStr}`;
        };

        return (
          <FormItem className="flex flex-col gap-2">
            <FormLabel className="text-base font-medium text-gray-700">
              {label}
            </FormLabel>

            <Popover>
              <PopoverTrigger asChild>
                <FormControl>
                  <Button
                    variant="outline"
                    className={cn(
                      "w-full justify-between px-3 py-2 text-left font-normal text-base",
                      !field.value && "text-muted-foreground",
                    )}
                  >
                    {getDateTimeDisplay()}
                    <CalendarIcon className="ml-2 h-4 w-4 text-gray-500" />
                  </Button>
                </FormControl>
              </PopoverTrigger>

              <PopoverContent
                className="w-auto max-w-[95vw] overflow-x-auto p-4"
                side="bottom"
                align="start"
                avoidCollisions={false}
              >
                <div className="min-w-[20rem] space-y-4">
                  {/* Date Picker */}
                  {isEthiopian ? (
                    <div className="flex flex-col gap-2">
                      <FormControl>
                        <EthiopianDatePickerModal
                          value={field.value}
                          onChange={handleEthiopianChange}
                        />
                      </FormControl>
                    </div>
                  ) : (
                    <Calendar
                      mode="single"
                      selected={field.value}
                      onSelect={field.onChange}
                      initialFocus
                      disabled={(date) =>
                        date < new Date(new Date().setHours(0, 0, 0, 0))
                      }
                    />
                  )}

                  {/* Time Picker — Ethiopian mode uses the Ethiopian-clock
                      picker inside EthiopianDatePickerModal above, so this
                      Gregorian-local time picker is only shown otherwise. */}
                  {!isEthiopian && field.value && (
                    <div className="border-t pt-4">
                      <div className="flex items-center gap-2 mb-3">
                        <Clock className="h-4 w-4 text-gray-500" />
                        <label className="text-sm font-medium text-gray-700">
                          {t("delegation.time") || "Time"}
                        </label>
                      </div>
                      <div className="flex gap-2 items-center">
                        <div className="flex-1">
                          <label className="text-xs text-gray-600 block mb-1">
                            {t("delegation.hours") || "Hours"}
                          </label>
                          <Input
                            type="number"
                            min="0"
                            max="23"
                            value={String(
                              new Date(field.value).getHours(),
                            ).padStart(2, "0")}
                            onChange={(e) =>
                              handleTimeChange(
                                e.target.value,
                                String(
                                  new Date(field.value).getMinutes(),
                                ).padStart(2, "0"),
                              )
                            }
                            className="text-center text-sm"
                            placeholder="00"
                          />
                        </div>
                        <div className="flex items-center justify-center pt-6">
                          :
                        </div>
                        <div className="flex-1">
                          <label className="text-xs text-gray-600 block mb-1">
                            {t("delegation.minutes") || "Minutes"}
                          </label>
                          <Input
                            type="number"
                            min="0"
                            max="59"
                            value={String(
                              new Date(field.value).getMinutes(),
                            ).padStart(2, "0")}
                            onChange={(e) =>
                              handleTimeChange(
                                String(
                                  new Date(field.value).getHours(),
                                ).padStart(2, "0"),
                                e.target.value,
                              )
                            }
                            className="text-center text-sm"
                            placeholder="00"
                          />
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </PopoverContent>
            </Popover>

            <FormMessage />
          </FormItem>
        );
      }}
    />
  );
};

export default DateTimeField;
