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

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

import { getProjectByIdentifierApi } from "@/app/utils/api/projectApi";
import { IssueData } from "@/app/utils/interface/issue";
import { useAppCache } from "@/app/utils/context/AppCacheContext";
import { useParams } from "next/navigation";
import { editIssueSchema } from "./schema";
import RiskWorkflow from "../../../riskTab/components/riskWorkflow";
import IssueWorkflow, { IssueStatus } from "../issueWorkflow";

interface EditIssueModalProps {
  open: boolean;
  onClose: () => void;
  issueData: IssueData;
  onSave: (updatedData: IssueData) => void;
}

type IssueFormStatus = z.infer<typeof editIssueSchema>["issueStatus"];

// Map any incoming status (legacy "open", differently-cased, etc.) to a valid
// enum value so the edit form doesn't fail zod validation on Save.
function normalizeIssueStatus(raw: string = ""): IssueFormStatus {
  const key = raw.toLowerCase().replace(/[-_]/g, " ").trim();
  const map: Record<string, IssueFormStatus> = {
    open: "Active",
    active: "Active",
    "on hold": "On hold",
    onhold: "On hold",
    resolved: "Resolved",
    closed: "Resolved",
  };
  return map[key] ?? "Active";
}

export default function EditIssueModal({
  open,
  onClose,
  issueData,
  onSave,
}: EditIssueModalProps) {
  const params = useParams();
  const { userNameMap } = useAppCache();

  const [assigneeOptions, setAssigneeOptions] = useState<string[]>([]);
  const [projectIdentifier] = useState(params.projectIdentifier as string);

  type EditIssueFormValues = z.infer<typeof editIssueSchema>;

  const form = useForm<EditIssueFormValues>({
    resolver: zodResolver(editIssueSchema),
    defaultValues: {
       issueStatus: normalizeIssueStatus(issueData.issueStatus),
      issueDescription: issueData.issueDescription,
      issueProbability: issueData.issueProbability,
      issueImpact: issueData.issueImpact,
      issueOwner: issueData.issueOwner,
    },
  });

  const { control, handleSubmit } = form;

  /* ---------- Project Team ---------- */
  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]);

  /* ---------- Submit ---------- */
  const onSubmit = (values: EditIssueFormValues) => {
    const { issueId, issueCreatedDate, ...cleanIssueData } = issueData;
console.log("Edit form ",values)
    onSave({
      ...cleanIssueData,
      ...values,
    });

    onClose();
  };

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

        <Separator />

        {/* Body */}
       <form
  onSubmit={handleSubmit(
    onSubmit,
    (errors) => {
      console.log("FORM ERRORS:", errors);
    }
  )}
  className="space-y-4"
>
          <FormField
            control={control}
            name="issueStatus"
            render={({ field }) => (
              <IssueWorkflow
                value={field.value as IssueStatus}
                onChange={field.onChange}
                standalone={false}
              />
            )}
          />

          {/* Title */}
          {/* <FormField
            control={control}
            name="issueTitle"
            render={({ field, fieldState }) => (
              <div className="space-y-1.5">
                <Label className="text-xs font-semibold">Title</Label>
                <Input {...field} className="text-sm h-9" />
                {fieldState.error && (
                  <p className="text-xs text-red-500">{fieldState.error.message}</p>
                )}
              </div>
            )}
          /> */}

          {/* Description */}
          <FormField
            control={control}
            name="issueDescription"
            render={({ field, fieldState }) => (
              <div className="space-y-2">
                <Label className="text-xs font-semibold">Description</Label>
                <Textarea
                  {...field}
                  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">
            <div className="col-span-2">
              <FormField
                control={control}
                name="issueProbability"
                render={({ field, fieldState }) => (
                  <div className="space-y-1.5">
                    <Label className="text-xs font-semibold">Probability</Label>
                    <Input
                      type="number"
                      min={0}
                      max={100}
                      value={field.value ?? ""}
                      onChange={(e) => field.onChange(Number(e.target.value))}
                      className="text-sm h-9"
                    />
                    {fieldState.error && (
                      <p className="text-xs text-red-500">
                        {fieldState.error.message}
                      </p>
                    )}
                  </div>
                )}
              />
            </div>

            <div className="col-span-8">
              <FormField
                control={control}
                name="issueImpact"
                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">
                          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>

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

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

                <Select onValueChange={field.onChange} value={field.value}>
                  <SelectTrigger className="text-sm h-9">
                    <SelectValue placeholder="Select Issue 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>
            )}
          />

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

          <Separator />

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