"use client";

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

import {
  Checkbox,
  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 { RiskData } from "@/app/utils/interface/risk";
import { getProjectByIdentifierApi } from "@/app/utils/api/projectApi";
import { useAppCache } from "@/app/utils/context/AppCacheContext";
import { riskSchema } from "./schema";

type FormValues = z.infer<typeof riskSchema>;

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

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

  const form = useForm<FormValues>({
    resolver: zodResolver(riskSchema),
    defaultValues: {
      riskTitle: "",
      riskProbability: 0,
      grossRiskValue: 0,
      probableRiskValue: 0,
      probableRiskValueInUSD: 0,
      riskImpact: "",
      riskOwner: "",
      riskDescription: "",
      projectIdentifier,
      financialRisk: false,
      riskCreatedDate: new Date().toISOString(),
      riskOptionsSelectId: "predefinedRisks",
      riskStatus: "identified",
      riskAge: 0,
      effectedSprintId: "",
    },
  });

  const probability = form.watch("riskProbability");
  const gross = form.watch("grossRiskValue");
  const createdDate = form.watch("riskCreatedDate");

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

  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const projectData = await getProjectByIdentifierApi(projectIdentifier);

        console.log("Project Data ", projectData);

        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]);

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

    form.setValue("probableRiskValue", probable);
    form.setValue("probableRiskValueInUSD", probable);
  }, [probability, gross, form]);

  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("riskAge", diff);
    }
  }, [createdDate, form]);

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

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(handleSubmit)}
        className="grid grid-cols-12 gap-4 "
      >
        {/* Risk Option */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="riskOptionsSelectId"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2 mt-2 ml-2">
                  Risk 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="predefinedRisks">
                      Predefined Risks
                    </SelectItem>
                    <SelectItem value="manualRisks">Manual Risks</SelectItem>
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />
        </div>

        {/* Risk Title */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="riskTitle"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">
                  Risk 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="riskProbability"
            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 Risk Value */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="grossRiskValue"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Gross Risk Value</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    value={field.value}
                    onChange={(e) => field.onChange(Number(e.target.value))}
                  />
                </FormControl>
              </FormItem>
            )}
          />
        </div>

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

        {/* Impact */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="riskImpact"
            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"
                        className="className=mb-1"
                      />
                    </SelectTrigger>
                  </FormControl>

                  <SelectContent>
                    <SelectItem value="Catastrophic Impact on Schedule/Cost to business/Quality/HSSE">
                      5: Catastrophic Impact on Schedule/Cost to
                      business/Quality/HSSE
                    </SelectItem>
                    <SelectItem value="High Impact on Schedule/Cost to business/Quality/HSSE">
                      4: High Impact on Schedule/Cost to business/Quality/HSSE
                    </SelectItem>
                    <SelectItem value="Medium Impact on Schedule/Cost to business/Quality/HSSE">
                      3: Medium Impact on Schedule/Cost to business/Quality/HSSE
                    </SelectItem>
                    <SelectItem value="Some impact">2: Some impact</SelectItem>
                    <SelectItem value="Little impact">
                      1: Little impact
                    </SelectItem>
                  </SelectContent>
                </Select>

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

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

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

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

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

        {/* Financial Risk */}
        <div className="col-span-6">
          <FormField
            control={form.control}
            name="financialRisk"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Financial Risk</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="riskCreatedDate"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Created On</FormLabel>
                <FormControl>
                  <Input
                    value={new Date(field.value).toLocaleDateString()}
                    disabled
                  />
                </FormControl>
              </FormItem>
            )}
          />
        </div>

        {/* Risk Status */}
        {/* <div className="col-span-6">
          <FormField
            control={form.control}
            name="riskStatus"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Risk Status</FormLabel>
                <Select
                  value={field.value}
                  onValueChange={field.onChange}
                >
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="Active">Active</SelectItem>
                    <SelectItem value="On hold">On Hold</SelectItem>
                    <SelectItem value="Resolved">Resolved</SelectItem>
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />
        </div> */}

        {/* Risk Age */}
        {/* <div className="col-span-6">
          <FormField
            control={form.control}
            name="riskAge"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">Risk Age (Days)</FormLabel>
                <FormControl>
                  <Input value={field.value} disabled />
                </FormControl>
              </FormItem>
            )}
          />
        </div> */}

        {/* Description */}
        <div className="col-span-12">
          <FormField
            control={form.control}
            name="riskDescription"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="mb-2">
                  Risk 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 Risk</Button>
        </div>
      </form>
    </Form>
  );
}
