import { useEffect, useState } from "react";
import {
  Button,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
  Label,
} from "ikoncomponents";
import { Separator } from "ikoncomponents";
import { Textarea } from "ikoncomponents";
import { Input } from "ikoncomponents";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "ikoncomponents";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "ikoncomponents";

import RiskWorkflow, { RiskStatus } from "../riskWorkflow";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import z from "zod";
import { editRiskSchema } from "./schema";
import { getProjectByIdentifierApi } from "@/app/utils/api/projectApi";
import { RiskData } from "@/app/utils/interface/risk";
import { useAppCache } from "@/app/utils/context/AppCacheContext";
import { useParams } from "next/navigation";

interface EditRiskModalProps {
  open: boolean;
  onClose: () => void;
  riskData: RiskData;
  onSave: (updatedData: RiskData) => void;
}

function normalizeStatus(raw: string = ""): RiskStatus {
  const map: Record<string, RiskStatus> = {
    identifier: "identified",
    identified: "identified",
    mitigation_planned: "mitigation_planned",
    mitigationplanned: "mitigation_planned",
    monitoring: "monitoring",
    closed: "closed",
  };
  return map[raw.toLowerCase().replace(/[\s-]/g, "_")] ?? "identified";
}

export default function EditRiskModal({
  open,
  onClose,
  riskData,
  onSave,
}: EditRiskModalProps) {
  const params = useParams();
  const { userNameMap } = useAppCache();

  const [assigneeOptions, setAssigneeOptions] = useState<string[]>([]);
  const [projectIdentifier, setProjectIdentifier] = useState(
    params.projectIdentifier as string,
  );
  console.log("Created risk data ", riskData);

  type EditRiskFormValues = z.infer<typeof editRiskSchema>;

  const form = useForm<EditRiskFormValues>({
    resolver: zodResolver(editRiskSchema),
    defaultValues: {
      riskDescription: riskData.riskDescription,
      riskProbability: riskData.riskProbability,
      riskImpact: String(riskData.riskImpact),
      riskOwner: riskData.riskOwner,
      riskStatus: normalizeStatus(riskData.riskStatus),
    },
  });

  const { control, handleSubmit } = form;

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

        console.log("Owner members ", uniqueAssignees);

        setAssigneeOptions(uniqueAssignees);
      } catch (error) {
        console.error("Error fetching project:", error);
      }
    };

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

  const onSubmit = (values: EditRiskFormValues) => {
    console.log("edit risk data update ", values);

    const { riskIdentifier, riskCreatedDate, ...cleanRiskData } = riskData;

    onSave({
      ...cleanRiskData,
      ...values,
    });

    onClose();
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-3xl!">
        {/* Header */}
        <DialogHeader>
          <DialogTitle className="text-base font-semibold">
            Edit Risk {riskData.projectIdentifier}
          </DialogTitle>
          <DialogDescription className="text-xs text-muted-foreground" />
        </DialogHeader>

        <Separator />

        {/* Body */}
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          {/* RiskWorkflow */}
          <FormField
            control={control}
            name="riskStatus"
            render={({ field }) => (
              <RiskWorkflow
                value={field.value}
                onChange={field.onChange}
                standalone={false}
              />
            )}
          />

          {/* Description */}
          <FormField
            control={control}
            name="riskDescription"
            render={({ field, fieldState }) => (
              <div className="space-y-2">
                <Label className="text-xs font-semibold">Description</Label>
                <Textarea
                  {...field}
                  placeholder="Describe the risk..."
                  className="resize-none text-sm min-h-[90px]"
                />
                {fieldState.error && (
                  <p className="text-xs text-red-500">
                    {fieldState.error.message}
                  </p>
                )}
              </div>
            )}
          />

          {/* Probability + Impact */}
          <div className="grid grid-cols-10 gap-4">
            {/* Probability (small) */}
            <div className="col-span-2">
              <FormField
                control={control}
                name="riskProbability"
                render={({ field, fieldState }) => (
                  <div className="space-y-1.5">
                    <Label className="text-xs font-semibold">Probability</Label>

                    <Input
                      type="number"
                      min={0}
                      max={100}
                      step={1}
                      value={field.value ?? ""}
                      onChange={(e) => field.onChange(Number(e.target.value))}
                      placeholder="Enter probability"
                      className="text-sm h-9"
                    />

                    {fieldState.error && (
                      <p className="text-xs text-red-500">
                        {fieldState.error.message}
                      </p>
                    )}
                  </div>
                )}
              />
            </div>

            {/* Impact (wide) */}
            <div className="col-span-8">
              <FormField
                control={control}
                name="riskImpact"
                render={({ field, fieldState }) => (
                  <div className="space-y-1.5">
                    <Label className="text-xs font-semibold">Impact</Label>

                    <Select value={field.value} onValueChange={field.onChange}>
                      <SelectTrigger className="text-sm h-9">
                        <SelectValue placeholder="Select..." />
                      </SelectTrigger>

                      <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>

                    {fieldState.error && (
                      <p className="text-xs text-red-500">
                        {fieldState.error.message}
                      </p>
                    )}
                  </div>
                )}
              />
            </div>
          </div>

          {/* Owner */}
          <div className="col-span-6">
            <FormField
              control={control}
              name="riskOwner"
              render={({ field, fieldState }) => (
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold">
                    Risk Owner <span className="text-red-500">*</span>
                  </Label>

                  <Select onValueChange={field.onChange} value={field.value}>
                    <SelectTrigger className="text-sm h-9">
                      <SelectValue placeholder="Select Risk Owner" />
                    </SelectTrigger>

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

                  {fieldState.error && (
                    <p className="text-xs text-red-500">
                      {fieldState.error.message}
                    </p>
                  )}
                </div>
              )}
            />
          </div>

          <Separator />

          {/* Footer */}
          <div className="flex justify-end gap-2 px-6 py-4">
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={onClose}
              className="h-9 px-4 text-sm"
            >
              Cancel
            </Button>
            <Button
              type="submit"
              size="sm"
              className="h-9 px-5 text-sm font-semibold"
            >
              Save Changes
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
