"use client";

import { AuthorizedAction } from "@/components/auth/authorized-action";
import { Datepicker } from "@/components/datepicker/datepicker";
import { ClientMultiSelector } from "@/components/shared/client-multi-selector";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Textarea } from "@/components/ui/textarea";
import { useProjectMutations } from "@/hooks/use-projects";
import { useRouter } from "@/i18n/routing";
import { CreateProjectRequest } from "@/lib/api/types";
import { formatDateToYMD, parseDateYMD } from "@/lib/date-utils";
import type { ActionSpec } from "@/lib/rbac/action-access";
import { cn } from "@/lib/utils";
import { User } from "@/types/user";
import { zodResolver } from "@hookform/resolvers/zod";
import { ChevronDown, X } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod";

type ProjectFormValues = {
  nameAr: string;
  nameEn: string;
  descriptionAr: string;
  descriptionEn: string;
  startDate: string;
  endDate: string;
  status: "not_started" | "in_progress" | "completed" | "delayed" | "planned";
  clientIds?: number[];
};

interface ProjectFormProps {
  initialValues?: Partial<ProjectFormValues>;
  onCancel?: () => void;
  submitLabel?: string;
  isEdit?: boolean;
  mutation: Partial<
    Pick<ReturnType<typeof useProjectMutations>, "createProject" | "updateProject" | "isLoading">
  >;
  projectId?: number | string;
  submitAction?: ActionSpec;
}

export function ProjectForm({
  initialValues,
  onCancel,
  submitLabel,
  isEdit = false,
  mutation,
  projectId,
  submitAction,
}: ProjectFormProps) {
  const t = useTranslations("projects.form");
  const router = useRouter();
  const locale = useLocale() as "ar" | "en";
  const [isClientsExpanded, setIsClientsExpanded] = useState(false);
  const [selectedClients, setSelectedClients] = useState<User[]>([]);

  // 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 defaultSubmitLabel = isEdit ? t("actions.save") : t("actions.submit");

  const redirectToProjects = () => {
    router.replace("/projects", { locale });
  };

  const projectFormSchema = z.object({
    nameAr: z.string().min(1, t("errors.nameArRequired")),
    nameEn: z.string().min(1, t("errors.nameEnRequired")),
    descriptionAr: z.string().min(1, t("errors.descriptionArRequired")),
    descriptionEn: z.string().min(1, t("errors.descriptionEnRequired")),
    startDate: z.string().min(1, t("errors.startDateRequired")),
    endDate: z.string().min(1, t("errors.endDateRequired")),
    status: z.enum([
      // "not_started",
      "in_progress",
      "completed",
      "delayed",
      "planned",
    ]),
    clientIds: z.array(z.number()).optional(),
  });

  const form = useForm<ProjectFormValues>({
    resolver: zodResolver(projectFormSchema),
    defaultValues: initialValues || {
      nameAr: "",
      nameEn: "",
      descriptionAr: "",
      descriptionEn: "",
      startDate: "",
      endDate: "",
      status: "planned",
      clientIds: [],
    },
  });

  // Reset form when initialValues changes (for edit mode)
  useEffect(() => {
    if (initialValues) {
      form.reset(initialValues);
    }
  }, [initialValues, form]);

  // Transform form values to API payload
  const transformFormData = (
    values: ProjectFormValues,
  ): CreateProjectRequest => {
    return {
      name_ar: values.nameAr,
      name_en: values.nameEn,
      description_ar: values.descriptionAr,
      description_en: values.descriptionEn,
      start_date: values.startDate,
      end_date: values.endDate,
      status: values.status,
      client_ids: values.clientIds || [],
    };
  };

  // Handle form submission
  const handleFormSubmit = async (values: ProjectFormValues) => {
    try {
      const payload = transformFormData(values);

      if (isEdit && projectId) {
        await mutation.updateProject?.(projectId, payload);
      } else {
        await mutation.createProject?.(payload);
      }

      redirectToProjects();
    } catch (error: unknown) {
      const errorMessage = (error as { message?: string })?.message || t("toast.error");
      toast.error(errorMessage);
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleFormSubmit)}>
        <Card className="border border-border rounded-2xl overflow-hidden mt-10">
          <CardHeader className="border-b border-border px-6 py-4">
            <CardTitle className="text-base font-semibold">
              {t("header")}
            </CardTitle>
          </CardHeader>

          <CardContent className="p-6 space-y-6">
            {/* Project Names */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <FormField
                control={form.control}
                name="nameAr"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("nameArLabel")}</span>
                    </FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="nameEn"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("nameEnLabel")}</span>
                    </FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Project Descriptions */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <FormField
                control={form.control}
                name="descriptionAr"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("descriptionArLabel")}</span>
                    </FormLabel>
                    <FormControl>
                      <Textarea
                        className="min-h-[96px] "
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="descriptionEn"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("descriptionEnLabel")}</span>
                    </FormLabel>
                    <FormControl>
                      <Textarea
                        className="min-h-[96px] "
                        
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Dates */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <FormField
                control={form.control}
                name="startDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("startDateLabel")}</span>
                    </FormLabel>
                    <FormControl>
                      <Datepicker
                        value={parseDate(field.value)}
                        onChange={(date) =>
                          field.onChange(formatDateToString(date))
                        }
                        locale={locale}
                        mode="single"
                        showShortcuts={false}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="endDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("endDateLabel")}</span>
                    </FormLabel>
                    <FormControl>
                      <Datepicker
                        value={parseDate(field.value)}
                        onChange={(date) =>
                          field.onChange(formatDateToString(date))
                        }
                        locale={locale}
                        mode="single"
                        showShortcuts={false}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Status */}
            <div className=" gap-8">
              <FormLabel className="text-base font-medium text-foreground">
                {t("statusLabel")}
              </FormLabel>

              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem className="space-y-3">
                    <FormControl>
                      <div
                        className={cn(
                          "flex",
                          locale === "ar" ? "items-start" : "items-end",
                        )}
                      >
                        <RadioGroup
                          dir={locale === "ar" ? "rtl" : "ltr"}
                          onValueChange={field.onChange}
                          value={field.value}
                          className="inline-flex max-w-full flex-wrap items-center gap-6"
                        >
                          <div className="flex items-center gap-2">
                            <label
                              htmlFor="delayed"
                              className="text-base font-medium text-muted-foreground cursor-pointer"
                            >
                              {t("status.delayed")}
                            </label>
                            <RadioGroupItem value="delayed" id="delayed" />
                          </div>
                          <div className="flex items-center gap-2">
                            <label
                              htmlFor="completed"
                              className="text-base font-medium text-muted-foreground cursor-pointer"
                            >
                              {t("status.completed")}
                            </label>
                            <RadioGroupItem value="completed" id="completed" />
                          </div>
                          <div className="flex items-center gap-2">
                            <label
                              htmlFor="in_progress"
                              className="text-base font-medium text-muted-foreground cursor-pointer"
                            >
                              {t("status.inProgress")}
                            </label>
                            <RadioGroupItem
                              value="in_progress"
                              id="in_progress"
                            />
                          </div>

                          <div className="flex items-center gap-2">
                            <label
                              htmlFor="planned"
                              className="text-base font-medium text-muted-foreground cursor-pointer"
                            >
                              {t("status.planned")}
                            </label>
                            <RadioGroupItem value="planned" id="planned" />
                          </div>
                        </RadioGroup>
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </CardContent>
        </Card>

        {/* Assign Clients Card */}
        <Card
          className={cn(
            "border border-border overflow-hidden mt-6",
            isClientsExpanded || selectedClients.length > 0
              ? "rounded-t-2xl rounded-b-2xl"
              : "rounded-2xl",
          )}
        >
          <button
            type="button"
            onClick={() => setIsClientsExpanded(!isClientsExpanded)}
            className="w-full"
          >
            <CardHeader
              className={cn(
                "px-6 py-4 ",
                (isClientsExpanded || selectedClients.length > 0) &&
                "border-b border-border",
              )}
            >
              <div className="flex items-center justify-between">
                <div className="md:flex items-center gap-2">
                  <CardTitle className="text-base font-semibold">
                    {t("assignClientsLabel")}
                  </CardTitle>
                  <span className="text-sm font-normal text-muted-foreground">
                    {t("assignClientsHint")}
                  </span>
                </div>
                <ChevronDown
                  className={cn(
                    "size-5 transition-transform text-foreground",
                    isClientsExpanded && "rotate-180",
                  )}
                />
              </div>
            </CardHeader>
          </button>

          {/* Selected Clients when collapsed */}
          {!isClientsExpanded && selectedClients.length > 0 && (
            <CardContent className="p-6 pt-4">
              <div className="flex flex-wrap gap-2">
                {selectedClients.map((user) => (
                  <Badge
                    key={user.id}
                    variant="secondary"
                    className="h-8 px-3 gap-1 rounded-full bg-secondary"
                  >
                    <span className="text-sm font-medium">{user.name}</span>
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        const currentIds = form.getValues("clientIds") || [];
                        form.setValue(
                          "clientIds",
                          currentIds.filter((id) => id !== user.id),
                        );
                        setSelectedClients(
                          selectedClients.filter((u) => u.id !== user.id),
                        );
                      }}
                    >
                      <X className="size-3 cursor-pointer" />
                    </button>
                  </Badge>
                ))}
              </div>
            </CardContent>
          )}

          {/* Expanded Content - Always render but hide when collapsed to populate selected users in edit mode */}
          <CardContent className={cn("p-6", !isClientsExpanded && "hidden")}>
            <FormField
              control={form.control}
              name="clientIds"
              render={({ field }) => (
                <FormItem>
                  <ClientMultiSelector
                    value={field.value || []}
                    onChange={field.onChange}
                    onSelectedUsersChange={setSelectedClients}
                    roleId={2}
                    showHeader={false}
                  />
                  <FormMessage />
                </FormItem>
              )}
            />
          </CardContent>
        </Card>

        {/* Form Actions */}
        <div className="flex items-center gap-4 justify-start mt-6">
          <AuthorizedAction
            action={
              submitAction ||
              {
                actionKey: isEdit ? "projects.update" : "projects.create",
                mode: "disable",
              }
            }
            surface="form"
          >
            <Button
              type="submit"
              className="h-10 px-4"
              disabled={mutation.isLoading}
            >
              {mutation.isLoading
                ? t("actions.loading")
                : submitLabel || defaultSubmitLabel}
            </Button>
          </AuthorizedAction>
          {onCancel && (
            <Button
              type="button"
              variant="outline"
              onClick={onCancel}
              className="h-10 px-4"
              disabled={mutation.isLoading}
            >
              {t("actions.cancel")}
            </Button>
          )}
        </div>
      </form>
    </Form>
  );
}
