"use client";

import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "ikoncomponents";

import { Input } from "ikoncomponents";
import { Textarea } from "ikoncomponents";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
} from "ikoncomponents";
import { Button } from "ikoncomponents";

import { IssueData } from "@/app/utils/interface/issue";
import { getProjectByIdentifierApi } from "@/app/utils/api/projectApi";
import { useAppCache } from "@/app/utils/context/AppCacheContext";
import { issueSchema } from "./schema";


type FormValues = z.infer<typeof issueSchema>;

interface Props {
  projectIdentifier: string;
  onSubmit: (data: IssueData) => void;
}

/* ---------------- Component ---------------- */

export default function IssueForm({ projectIdentifier, onSubmit }: Props) {
  const { userNameMap } = useAppCache();

  const form = useForm<FormValues>({
    resolver: zodResolver(issueSchema),
    defaultValues: {
      issueTitle: "",
      issueProbability: 0,

      grossIssueValue: 0,
      probableIssueValue: 0,
      probableIssueValueInUSD: 0,

      issueImpact: "",
      issueOwner: "",
      issueDescription: "",

      projectIdentifier,
      financialIssue: false,

      issueCreatedDate: new Date().toISOString(),
      issueOptionsSelectId: "manualIssues",

      issueStatus: "Active",
      issueAge: 0,
      effectedSprintId: "",
    },
  });

  const probability = form.watch("issueProbability");
  const gross = form.watch("grossIssueValue");
  const createdDate = form.watch("issueCreatedDate");

  const [assigneeOptions, setAssigneeOptions] = useState<string[]>([]);

  /* -------- Project Users -------- */
  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const projectData = await getProjectByIdentifierApi(projectIdentifier);

        const {
          projectTeam = [],
          projectTeamUnderProjectManager = [],
          projectManagerDelegates,
        } = projectData;

        const managerDelegatesArr = projectManagerDelegates
          ? Array.isArray(projectManagerDelegates)
            ? projectManagerDelegates
            : [projectManagerDelegates]
          : [];

        const mergedAssignees = [
          ...projectTeam,
          ...projectTeamUnderProjectManager,
          ...managerDelegatesArr,
        ];

        const uniqueAssignees = [...new Set(mergedAssignees)];
        setAssigneeOptions(uniqueAssignees);
      } catch (error) {
        console.error("Error fetching project:", error);
      }
    };

    if (projectIdentifier) fetchProjects();
  }, [projectIdentifier]);

  /* -------- Calculations -------- */
  useEffect(() => {
    const probable =
      probability && gross ? (probability * gross) / 100 : 0;

    form.setValue("probableIssueValue", probable);
    form.setValue("probableIssueValueInUSD", probable);
  }, [probability, gross, form]);

  /* -------- Issue Age -------- */
  useEffect(() => {
    if (!createdDate) return;

    const created = new Date(createdDate);
    const today = new Date();
    const diff = Math.floor(
      (today.getTime() - created.getTime()) / (1000 * 60 * 60 * 24)
    );

    if (diff >= 0) {
      form.setValue("issueAge", diff);
    }
  }, [createdDate, form]);

  /* -------- Submit -------- */
  const handleSubmit = (data: FormValues) => {
    onSubmit(data);
    form.reset();
  };

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(handleSubmit)}
        className="grid grid-cols-12 gap-4"
      >
        {/* Issue Option */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="issueOptionsSelectId"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2 mt-2 ml-2">
                  Issue Options <span className="text-red-500">*</span>
                </FormLabel>
                <Select value={field.value} onValueChange={field.onChange}>
                  <FormControl className="w-full">
                    <SelectTrigger className="w-full">
                      <SelectValue />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="manualIssues">Manual Issues</SelectItem>
                    <SelectItem value="predefinedIssues">Predefined Issues</SelectItem>
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />
        </div>

        {/* Issue Title */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="issueTitle"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">
                  Issue Title <span className="text-red-500">*</span>
                </FormLabel>
                <FormControl>
                  <Input {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* Probability */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="issueProbability"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">
                  Probability % <span className="text-red-500">*</span>
                </FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    value={field.value}
                    onChange={(e) =>
                      field.onChange(Number(e.target.value))
                    }
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* Gross Value */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="grossIssueValue"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Gross Issue Value</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    value={field.value}
                    onChange={(e) =>
                      field.onChange(Number(e.target.value))
                    }
                  />
                </FormControl>
              </FormItem>
            )}
          />
        </div>

        {/* Probable Value */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="probableIssueValue"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Probable Issue Value</FormLabel>
                <FormControl>
                  <Input type="number" value={field.value} disabled />
                </FormControl>
              </FormItem>
            )}
          />
        </div>

        {/* Impact */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="issueImpact"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">
                  Impact (1–5) <span className="text-red-500">*</span>
                </FormLabel>

                <Select
                  onValueChange={(value) => field.onChange(String(value))}
                  defaultValue={field.value?.toString()}
                >
                  <FormControl className="w-full">
                    <SelectTrigger className="w-full">
                      <SelectValue placeholder="Select Impact" />
                    </SelectTrigger>
                  </FormControl>

                  <SelectContent>
                    <SelectItem value="Catastrophic">5: Catastrophic</SelectItem>
                    <SelectItem value="High">4: High</SelectItem>
                    <SelectItem value="Medium">3: Medium</SelectItem>
                    <SelectItem value="Low">2: Low</SelectItem>
                    <SelectItem value="Minimal">1: Minimal</SelectItem>
                  </SelectContent>
                </Select>

                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* Issue Owner */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="issueOwner"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">
                  Issue Owner <span className="text-red-500">*</span>
                </FormLabel>

                <FormControl>
                  <Select onValueChange={field.onChange} value={field.value}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select Issue Owner" />
                    </SelectTrigger>

                    <SelectContent>
                      {assigneeOptions.map((id) => (
                        <SelectItem key={id} value={id}>
                          {userNameMap.get(id) || "Loading..."}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </FormControl>

                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* Financial Issue */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="financialIssue"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Financial Issue</FormLabel>
                <Select
                  value={String(field.value)}
                  onValueChange={(val) =>
                    field.onChange(val === "true")
                  }
                >
                  <FormControl className="w-full">
                    <SelectTrigger className="w-full">
                      <SelectValue />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="false">No</SelectItem>
                    <SelectItem value="true">Yes</SelectItem>
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />
        </div>

        {/* Created Date */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="issueCreatedDate"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Created On</FormLabel>
                <FormControl>
                  <Input
                    value={new Date(field.value).toLocaleDateString()}
                    disabled
                  />
                </FormControl>
              </FormItem>
            )}
          />
        </div>

        {/* Description */}
        <div className="col-span-12">
          <FormField
            control={form.control}
            name="issueDescription"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">
                  Issue Description <span className="text-red-500">*</span>
                </FormLabel>
                <FormControl>
                  <Textarea rows={4} {...field} />
                </FormControl>
              </FormItem>
            )}
          />
        </div>

        <div className="col-span-12 flex justify-end">
          <Button type="submit">Add Issue</Button>
        </div>
      </form>
    </Form>
  );
}