"use client";
// src/app/tasks/new/page.tsx
import { useState, useEffect, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { AppShell } from "@/components/layout/AppShell";
import { Input, Select, Textarea, Button, Card, CardHeader, CardTitle, CardContent } from "@/components/ui/index";
import { createTaskFormSchema, type TaskFormValues } from "@/lib/validations";
import { useLanguage } from "@/i18n/LanguageContext";
import { useAuth } from "@/hooks/useAuth";
import { toast } from "sonner";
import { EntityCustomFieldsFormInputs } from "@/components/custom-fields/EntityCustomFieldsSection";
import type { CustomFieldDefinitionDto } from "@/lib/customFields.shared";

export default function NewTaskPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { user } = useAuth();
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const [users, setUsers] = useState<any[]>([]);
  const [leads, setLeads] = useState<any[]>([]);
  const [opportunities, setOpportunities] = useState<any[]>([]);
  const [cfDefinitions, setCfDefinitions] = useState<CustomFieldDefinitionDto[]>([]);

  useEffect(() => {
    fetch("/api/custom-fields?entity=Task")
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((j) => {
        const defs = j.data?.definitions;
        if (!Array.isArray(defs)) return;
        setCfDefinitions(defs);
      })
      .catch(() => {});
  }, []);

  const taskSchemaResolved = useMemo(() => createTaskFormSchema(t, cfDefinitions), [t, cfDefinitions]);

  const PRIORITY_OPTIONS = useMemo(
    () => [
      { value: "LOW", label: t("tasks.priorityLow") },
      { value: "MEDIUM", label: t("tasks.priorityMedium") },
      { value: "HIGH", label: t("tasks.priorityHigh") },
      { value: "URGENT", label: t("tasks.priorityUrgent") },
    ],
    [t]
  );

  const STATUS_OPTIONS = useMemo(
    () => [
      { value: "TODO", label: t("tasks.statusTodo") },
      { value: "IN_PROGRESS", label: t("tasks.statusInProgress") },
      { value: "DONE", label: t("tasks.statusDone") },
      { value: "CANCELLED", label: t("tasks.statusCancelled") },
    ],
    [t]
  );

  const leadIdParam = searchParams.get("leadId") ?? "";
  const opportunityIdParam = searchParams.get("opportunityId") ?? "";

  const mergedDefaults = useMemo(() => {
    const cf: Record<string, string> = {};
    for (const d of cfDefinitions) {
      cf[d.fieldName] = "";
    }
    return {
      title: "",
      description: "",
      status: "TODO" as const,
      priority: "MEDIUM" as const,
      dueDate: "",
      assignedToId: user?.id ?? "",
      leadId: leadIdParam,
      opportunityId: opportunityIdParam,
      customFields: cf,
    } satisfies TaskFormValues;
  }, [cfDefinitions, user?.id, leadIdParam, opportunityIdParam]);

  const { register, handleSubmit, control, reset, formState: { errors } } = useForm<TaskFormValues>({
    resolver: zodResolver(taskSchemaResolved),
    defaultValues: mergedDefaults,
  });

  useEffect(() => {
    reset(mergedDefaults);
  }, [mergedDefaults, reset]);

  useEffect(() => {
    Promise.all([
      fetch("/api/users/assignable?pageSize=100").then(r => r.json()),
      fetch("/api/leads?pageSize=200").then(r => r.json()),
      fetch("/api/deals?pageSize=200").then(r => r.json()),
    ]).then(([u, l, o]) => {
      setUsers(u.data?.items ?? []);
      setLeads(l.data?.items ?? []);
      setOpportunities(o.data?.items ?? []);
    }).catch(() => {});
  }, []);

  const onSubmit = async (data: TaskFormValues) => {
    setIsLoading(true);
    try {
      const { customFields, ...rest } = data;
      const payload: Record<string, unknown> = { ...rest };
      if (cfDefinitions.length > 0) {
        payload.customFields = customFields;
      }
      const res = await fetch("/api/tasks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? t("toast.failed"));
      toast.success(t("toast.taskCreated"));
      router.push("/tasks");
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <AppShell breadcrumbs={[
      { label: t("nav.tasks"), href: "/tasks" },
      { label: t("tasks.new") },
    ]}>
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold text-foreground">{t("tasks.createPageTitle")}</h1>
        </div>

        <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>{t("tasks.formDetailsCard")}</CardTitle>
            </CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Input
                label={t("tasks.fieldTitle")}
                required
                className="sm:col-span-2"
                placeholder={t("tasks.titlePlaceholder")}
                error={errors.title?.message}
                {...register("title")}
              />
              <Controller
                name="priority"
                control={control}
                render={({ field }) => (
                  <Select
                    label={t("common.priority")}
                    required
                    options={PRIORITY_OPTIONS}
                    error={errors.priority?.message}
                    value={field.value}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                  />
                )}
              />
              <Controller
                name="status"
                control={control}
                render={({ field }) => (
                  <Select
                    label={t("common.status")}
                    required
                    options={STATUS_OPTIONS}
                    error={errors.status?.message}
                    value={field.value}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                  />
                )}
              />
              <Input
                label={t("tasks.dueDate")}
                type="date"
                error={errors.dueDate?.message}
                {...register("dueDate")}
              />
              <Controller
                name="assignedToId"
                control={control}
                render={({ field }) => (
                  <Select
                    label={t("common.assignedTo")}
                    options={users.map(u => ({ value: u.id, label: u.name }))}
                    placeholder={t("deals.unassigned")}
                    value={field.value ?? ""}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                  />
                )}
              />
              <EntityCustomFieldsFormInputs definitions={cfDefinitions} register={register} errors={errors} />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>{t("tasks.relatedOptional")}</CardTitle>
            </CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Controller
                name="leadId"
                control={control}
                render={({ field }) => (
                  <Select
                    label={t("tasks.fieldLead")}
                    options={leads.map(l => ({ value: l.id, label: `${l.firstName} ${l.lastName}` }))}
                    placeholder={t("tasks.none")}
                    value={field.value ?? ""}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                  />
                )}
              />
              <Controller
                name="opportunityId"
                control={control}
                render={({ field }) => (
                  <Select
                    label={t("tasks.fieldOpportunity")}
                    options={opportunities.map(o => ({ value: o.id, label: o.title }))}
                    placeholder={t("tasks.none")}
                    value={field.value ?? ""}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                  />
                )}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>{t("tasks.descCard")}</CardTitle>
            </CardHeader>
            <CardContent>
              <Textarea
                placeholder={t("tasks.descPlaceholder")}
                rows={3}
                {...register("description")}
              />
            </CardContent>
          </Card>

          <div className="flex justify-end gap-3">
            <Button type="button" variant="outline" onClick={() => router.back()} disabled={isLoading}>
              {t("common.cancel")}
            </Button>
            <Button type="submit" loading={isLoading}>
              {t("tasks.createBtn")}
            </Button>
          </div>
        </form>
      </div>
    </AppShell>
  );
}
