"use client";

import React from "react";
import { Input, Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "ikoncomponents";
import { ActionItem, ActionsData } from "../../types";
import { StepErrors } from "../../lib/validation";
import { useAppCache } from "@/app/utils/context/AppCacheContext";

interface ActionsStepProps {
  data: ActionsData;
  onChange: (field: keyof ActionsData, value: ActionItem[]) => void;
  errors: StepErrors;
}

const rowError = (errors: StepErrors, idx: number, field: string): string | undefined =>
  errors[`actions.${idx}.${field}`];

const FieldError = ({ message }: { message?: string }) =>
  message ? <p className="text-xs text-destructive mt-1">{message}</p> : null;

const ActionsStep: React.FC<ActionsStepProps> = ({ data, onChange, errors }) => {
  // activeUsers is already filtered to active, non-deleted users by the cache.
  const { activeUsers } = useAppCache();

  const addAction = () =>
    onChange("actions", [...data.actions, { item: "", responsible: "", dueDate: "" }]);

  const updateAction = (idx: number, field: keyof ActionItem, val: string) => {
    const updated = data.actions.map((a, i) => (i === idx ? { ...a, [field]: val } : a));
    onChange("actions", updated);
  };

  const removeAction = (idx: number) => {
    onChange("actions", data.actions.filter((_, i) => i !== idx));
  };

  return (
    <div className="space-y-3">
      <table className="w-full border-collapse">
        <thead>
          <tr>
            <th className="text-left text-sm font-medium text-slate-700 pb-2 pr-3 w-[48px]">SI No</th>
            <th className="text-left text-sm font-medium text-slate-700 pb-2 pr-8">
              Item <span className="text-destructive">*</span>
            </th>
            <th className="text-left text-sm font-medium text-slate-700 pb-2 pr-8">
              Responsible <span className="text-destructive">*</span>
            </th>
            <th className="text-left text-sm font-medium text-slate-700 pb-2 pr-3 w-[150px]">
              Due Date <span className="text-destructive">*</span>
            </th>
            <th className="pb-2 w-[40px] text-right">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={addAction}
                className="text-emerald-600 border-emerald-500 hover:bg-emerald-50 text-xs px-2 py-1"
              >
                + ADD
              </Button>
            </th>
          </tr>
        </thead>

        <tbody>
          {data.actions.map((action, idx) => (
            <tr key={idx} className="align-top">
              <td className="pr-3 pb-2 text-sm text-muted-foreground font-medium pt-2">{idx + 1}</td>

              {/* Item */}
              <td className="pr-8 pb-2">
                <Input
                  value={action.item}
                  onChange={(e) => updateAction(idx, "item", e.target.value)}
                  placeholder="Action item"
                  className={`h-9 ${rowError(errors, idx, "item") ? "border-destructive" : ""}`}
                />
                <FieldError message={rowError(errors, idx, "item")} />
              </td>

              {/* Responsible */}
              <td className="pr-8 pb-2">
                <Select
                  value={action.responsible}
                  onValueChange={(v) => updateAction(idx, "responsible", v)}
                >
                  <SelectTrigger className={`h-9 ${rowError(errors, idx, "responsible") ? "border-destructive" : ""}`}>
                    <SelectValue placeholder="Select Responsible" />
                  </SelectTrigger>
                  <SelectContent side="bottom" position="popper" sideOffset={4} className="max-h-56 overflow-y-auto">
                    {activeUsers.map((user) => (
                      <SelectItem key={user.userId} value={user.userId}>
                        {user.userName}
                        {user.userDesignation ? ` (${user.userDesignation})` : ""}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError message={rowError(errors, idx, "responsible")} />
              </td>

              {/* Due Date */}
              <td className="pr-3 pb-2">
                <Input
                  type="date"
                  value={action.dueDate}
                  onChange={(e) => updateAction(idx, "dueDate", e.target.value)}
                  className={`h-9 ${rowError(errors, idx, "dueDate") ? "border-destructive" : ""}`}
                />
                <FieldError message={rowError(errors, idx, "dueDate")} />
              </td>

              {/* Remove */}
              <td className="pb-2 text-right">
                {data.actions.length > 1 && (
                  <button
                    type="button"
                    onClick={() => removeAction(idx)}
                    className="text-muted-foreground hover:text-destructive transition-colors text-xl leading-none mt-1"
                  >
                    ×
                  </button>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default ActionsStep;