"use client";

import { AuthorizedAction } from "@/components/auth/authorized-action";
import { useEffect } from "react";
import { Controller, useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { formatDateToYMD, parseDateYMD } from "@/lib/date-utils";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Datepicker } from "@/components/datepicker/datepicker";
import { useLocale } from "next-intl";
import type { ActionSpec } from "@/lib/rbac/action-access";
import { cn } from "@/lib/utils";
import { useMemo } from "react";
import { PhaseStatusSelector, type PhaseStatus } from "./phase-status-selector";

interface PhaseFormData {
  name: string;
  name_ar: string;
  name_en: string;
  description: string;
  description_ar: string;
  description_en: string;
  status: PhaseStatus;
  startDate: string;
  endDate: string;
  autoCalculateProgress?: boolean;
}

interface EditPhaseDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  initialData: PhaseFormData;
  onSubmit: (data: PhaseFormData) => void;
  minStartDate?: string;
  maxDate?: string;
  submitAction?: ActionSpec;
  translations: {
    title: string;
    nameLabel: string;
    namePlaceholder?: string;
    nameArLabel?: string;
    nameEnLabel?: string;
    descriptionLabel: string;
    descriptionPlaceholder?: string;
    descriptionArLabel?: string;
    descriptionEnLabel?: string;
    statusLabel?: string;
    statusPlaceholder?: string;
    startDateLabel: string;
    endDateLabel: string;
    datePlaceholder?: string;
    autoProgressLabel: string;
    dateBeforeProjectCreated?: string;
    startDateBeforeProjectCreated?: string;
    dateAfterProjectDeadline?: string;
    saveButton: string;
    cancelButton: string;
  };
}

export function EditPhaseDialog({
  open,
  onOpenChange,
  initialData,
  onSubmit,
  minStartDate,
  maxDate,
  submitAction,
  translations,
}: EditPhaseDialogProps) {
  const locale = useLocale() as "ar" | "en";
  const normalizedMinStartDate =
    minStartDate && /^\d{4}-\d{2}-\d{2}$/.test(minStartDate)
      ? minStartDate
      : undefined;
  const normalizedMaxDate =
    maxDate && /^\d{4}-\d{2}-\d{2}$/.test(maxDate) ? maxDate : undefined;
  const dateBeforeProjectCreatedMessage =
    translations.dateBeforeProjectCreated ||
    translations.startDateBeforeProjectCreated ||
    (locale === "ar"
      ? "لا يمكن أن يكون التاريخ قبل تاريخ إنشاء المشروع"
      : "Date cannot be before the project creation date");
  const dateAfterProjectDeadlineMessage =
    translations.dateAfterProjectDeadline ||
    (locale === "ar"
      ? "لا يمكن أن يكون التاريخ بعد الموعد النهائي للمشروع"
      : "Date cannot be after the project deadline");
  const phaseFormSchema = useMemo(
    () =>
      z
        .object({
          name: z.string().optional(),
          name_ar: z.string().trim().min(1),
          name_en: z.string().trim().min(1),
          description: z.string().optional(),
          description_ar: z.string().trim().min(1),
          description_en: z.string().trim().min(1),
          status: z.enum(["not_started", "in_progress", "completed", "delayed"]),
          startDate: z.string().min(1),
          endDate: z.string().min(1),
          autoCalculateProgress: z.boolean().optional(),
        })
        .superRefine((data, ctx) => {
          if (
            normalizedMinStartDate &&
            data.startDate &&
            data.startDate < normalizedMinStartDate
          ) {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              path: ["startDate"],
              message: dateBeforeProjectCreatedMessage,
            });
          }

          if (
            normalizedMinStartDate &&
            data.endDate &&
            data.endDate < normalizedMinStartDate
          ) {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              path: ["endDate"],
              message: dateBeforeProjectCreatedMessage,
            });
          }

          if (normalizedMaxDate && data.startDate && data.startDate > normalizedMaxDate) {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              path: ["startDate"],
              message: dateAfterProjectDeadlineMessage,
            });
          }

          if (normalizedMaxDate && data.endDate && data.endDate > normalizedMaxDate) {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              path: ["endDate"],
              message: dateAfterProjectDeadlineMessage,
            });
          }
        }),
    [
      dateAfterProjectDeadlineMessage,
      dateBeforeProjectCreatedMessage,
      normalizedMaxDate,
      normalizedMinStartDate,
    ],
  );

  // Helper to parse date string (YYYY-MM-DD) to local Date
  const parseDate = (dateStr: string | undefined): Date | null => {
    return parseDateYMD(dateStr);
  };

  // Helper to format Date to YYYY-MM-DD using local date parts
  const formatDateToString = (date: Date | null): string => {
    return formatDateToYMD(date);
  };

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    formState: { errors },
  } = useForm<PhaseFormData>({
    resolver: zodResolver(phaseFormSchema),
    defaultValues: initialData,
  });

  const selectedStatus = useWatch({
    control,
    name: "status",
  });
  const startDate = useWatch({
    control,
    name: "startDate",
  });
  const endDate = useWatch({
    control,
    name: "endDate",
  });

  // Reset form when initialData changes
  useEffect(() => {
    reset(initialData);
  }, [initialData, reset]);

  // Sync Datepicker state with react-hook-form
  const handleStartDateChange = (date: Date | null) => {
    setValue("startDate", formatDateToString(date), {
      shouldDirty: true,
      shouldValidate: true,
    });
  };

  const handleEndDateChange = (date: Date | null) => {
    setValue("endDate", formatDateToString(date), {
      shouldDirty: true,
      shouldValidate: true,
    });
  };

  const handleFormSubmit = (data: PhaseFormData) => {
    const formData = {
      ...data,
      name: data.name_ar, // Use Arabic name as primary
      startDate: data.startDate,
      endDate: data.endDate,
    };
    onSubmit(formData);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[656px]">
        <DialogHeader className="border-border">
          <DialogTitle>{translations.title}</DialogTitle>
        </DialogHeader>

        <form
          onSubmit={handleSubmit(handleFormSubmit)}
          className="flex min-h-0 flex-1 flex-col"
        >
          <DialogBody className="space-y-4">
            {/* Phase Names - Two Column Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {/* Arabic Name */}
              <div className="space-y-2">
                <Label htmlFor="name_ar" className="flex gap-1">
                  <span className="text-destructive">*</span>
                  <span>{locale === "ar" ? "اسم المرحلة (AR)" : "Phase Name (AR)"}</span>
                </Label>
                <Controller
                  control={control}
                  name="name_ar"
                  render={({ field }) => (
                    <Input
                      id="name_ar"
                      className={cn(errors.name_ar && "border-destructive")}
                      {...field}
                    />
                  )}
                />
                {errors.name_ar && (
                  <p className="text-sm text-destructive">{errors.name_ar.message}</p>
                )}
              </div>

              {/* English Name */}
              <div className="space-y-2">
                <Label htmlFor="name_en" className="flex gap-1">
                  <span className="text-destructive">*</span>
                  <span>{locale === "ar" ? "اسم المرحلة (EN)" : "Phase Name (EN)"}</span>
                </Label>
                <Controller
                  control={control}
                  name="name_en"
                  render={({ field }) => (
                    <Input
                      id="name_en"
                      className={cn(errors.name_en && "border-destructive")}
                      {...field}
                    />
                  )}
                />
                {errors.name_en && (
                  <p className="text-sm text-destructive">{errors.name_en.message}</p>
                )}
              </div>
            </div>

            {/* Descriptions - Two Column Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {/* Arabic Description */}
              <div className="space-y-2">
                <Label htmlFor="description_ar" className="flex gap-1">
                  <span className="text-destructive">*</span>
                  <span>{locale === "ar" ? "وصف المرحلة (AR)" : "Description (AR)"}</span>
                </Label>
                <Controller
                  control={control}
                  name="description_ar"
                  render={({ field }) => (
                    <Textarea
                      id="description_ar"
                      rows={3}
                      {...field}
                    />
                  )}
                />
                {errors.description_ar && (
                  <p className="text-sm text-destructive">
                    {errors.description_ar.message}
                  </p>
                )}
              </div>

              {/* English Description */}
              <div className="space-y-2">
                <Label htmlFor="description_en" className="flex gap-1">
                  <span className="text-destructive">*</span>
                  <span>{locale === "ar" ? "وصف المرحلة (EN)" : "Description (EN)"}</span>
                </Label>
                <Controller
                  control={control}
                  name="description_en"
                  render={({ field }) => (
                    <Textarea
                      id="description_en"
                      rows={3}
                      {...field}
                    />
                  )}
                />
                {errors.description_en && (
                  <p className="text-sm text-destructive">
                    {errors.description_en.message}
                  </p>
                )}
              </div>
            </div>

            {/* Status */}
            <div className="space-y-2">
              <Label htmlFor="phase-status" className="flex gap-1">
                <span className="text-destructive">*</span>
                <span>{translations.statusLabel || (locale === "ar" ? "حالة المرحلة" : "Phase Status")}</span>
              </Label>
              <PhaseStatusSelector
                value={selectedStatus}
                onChange={(value: PhaseStatus) =>
                  setValue("status", value, {
                    shouldDirty: true,
                    shouldValidate: true,
                  })
                }
                locale={locale}
                placeholder={translations.statusPlaceholder || (locale === "ar" ? "اختر الحالة" : "Select status")}
              />
            </div>

            {/* Date Fields - Two Column Grid */}
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              {/* Start Date */}
              <div className="space-y-2">
                <Label htmlFor="startDate" className="flex gap-1">
                  <span className="text-destructive">*</span>
                  <span>{translations.startDateLabel}</span>
                </Label>
                  <Datepicker
                    value={parseDate(startDate)}
                    onChange={handleStartDateChange}
                    locale={locale}
                    mode="single"
                    showShortcuts={false}
                    minDate={parseDateYMD(normalizedMinStartDate) ?? undefined}
                    maxDate={parseDateYMD(normalizedMaxDate) ?? undefined}
                  />
                {normalizedMinStartDate && normalizedMaxDate && (
                  <p className="text-[10px] text-muted-foreground">
                    {locale === "ar"
                      ? `النطاق المتاح: ${normalizedMinStartDate} إلى ${normalizedMaxDate}`
                      : `Valid range: ${normalizedMinStartDate} to ${normalizedMaxDate}`}
                  </p>
                )}
                {errors.startDate && (
                  <p className="text-sm text-destructive">
                    {errors.startDate.message}
                  </p>
                )}
              </div>

              {/* End Date */}
              <div className="space-y-2">
                <Label htmlFor="endDate" className="flex gap-1">
                  <span className="text-destructive">*</span>
                  <span>{translations.endDateLabel}</span>
                </Label>
                  <Datepicker
                    value={parseDate(endDate)}
                    onChange={handleEndDateChange}
                    locale={locale}
                    mode="single"
                    showShortcuts={false}
                    minDate={parseDateYMD(normalizedMinStartDate) ?? undefined}
                    maxDate={parseDateYMD(normalizedMaxDate) ?? undefined}
                  />
                {normalizedMinStartDate && normalizedMaxDate && (
                  <p className="text-[10px] text-muted-foreground">
                    {locale === "ar"
                      ? `النطاق المتاح: ${normalizedMinStartDate} إلى ${normalizedMaxDate}`
                      : `Valid range: ${normalizedMinStartDate} to ${normalizedMaxDate}`}
                  </p>
                )}
                {errors.endDate && (
                  <p className="text-sm text-destructive">
                    {errors.endDate.message}
                  </p>
                )}
              </div>
            </div>

          </DialogBody>

          <DialogFooter className="justify-start">
            <div className="flex gap-4 w-full justify-start">
              <AuthorizedAction
                action={
                  submitAction || {
                    actionKey: "phases.update",
                    mode: "disable",
                  }
                }
                surface="form"
              >
                <Button type="submit">{translations.saveButton}</Button>
              </AuthorizedAction>
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
              >
                {translations.cancelButton}
              </Button>
            </div>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
