"use client";

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

interface AttendeesStepProps {
  data: AttendeesData;
  onChange: (field: keyof AttendeesData, value: Attendee[]) => void;
  onUsersLoaded: (users: ApiUser[]) => void;
  errors: StepErrors;
}

// e.g. errors["attendees.0.name"] or errors["attendees.0.role"]
const rowError = (errors: StepErrors, idx: number, field: string): string | undefined =>
  errors[`attendees.${idx}.${field}`];

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

const AttendeesStep: React.FC<AttendeesStepProps> = ({ data, onChange, onUsersLoaded, errors }) => {
  const { activeUsers } = useAppCache();

  useEffect(() => {
    // activeUsers is already filtered to active, non-deleted users by the cache.
    const apiUsers: ApiUser[] = activeUsers.map((u) => ({ ...u, userPhone: u.userPhone ?? "" }));
    onUsersLoaded(apiUsers);
  }, [activeUsers]);

  const addAttendee = () =>
    onChange("attendees", [...data.attendees, { name: "", role: "", contact: "" }]);

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

  const removeAttendee = (idx: number) => {
    onChange("attendees", data.attendees.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-8 w-[35%]">
              Name <span className="text-destructive">*</span>
            </th>
            <th className="text-left text-sm font-medium text-slate-700 pb-2 pr-3 w-[30%]">
              Dept./Role <span className="text-destructive">*</span>
            </th>
            <th className="text-left text-sm font-medium text-slate-700 pb-2 pr-3 w-[30%]">
              Contact
            </th>
            <th className="pb-2 w-[40px] text-right">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={addAttendee}
                className="text-emerald-600 border-emerald-500 hover:bg-emerald-50 text-xs px-2 py-1"
              >
                + ADD
              </Button>
            </th>
          </tr>
        </thead>

        <tbody>
          {data.attendees.map((att, idx) => (
            <tr key={idx} className="align-top">
              {/* Attendee Name */}
              <td className="pr-8 pb-2">
                <Select
                  value={att.name || ""}
                  onValueChange={(v) => updateAttendee(idx, "name", v)}
                >
                  <SelectTrigger className={`w-full h-9 ${rowError(errors, idx, "name") ? "border-destructive" : ""}`}>
                    <SelectValue
                      placeholder={
                        activeUsers.length === 0 ? "No users found" : "Select Attendee Name"
                      }
                    />
                  </SelectTrigger>
                  <SelectContent side="bottom" position="popper" className="w-full max-h-60 overflow-y-auto">
                    {activeUsers.length === 0 && (
                      <div className="px-2 py-1 text-sm text-muted-foreground">No active users available</div>
                    )}
                    {activeUsers.map((user) => (
                      <SelectItem key={user.userId} value={String(user.userId)} className="truncate">
                        {user.userName}
                        {user.userDesignation ? ` (${user.userDesignation})` : ""}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError message={rowError(errors, idx, "name")} />
              </td>

              {/* Role */}
              <td className="pr-3 pb-2">
                <Select
                  value={att.role}
                  onValueChange={(v) => updateAttendee(idx, "role", v)}
                >
                  <SelectTrigger className={`h-9 ${rowError(errors, idx, "role") ? "border-destructive" : ""}`}>
                    <SelectValue placeholder="Select Attendee Role" />
                  </SelectTrigger>
                  <SelectContent side="bottom" position="popper" className="max-h-60 overflow-y-auto">
                    {ROLE_OPTIONS.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError message={rowError(errors, idx, "role")} />
              </td>

              {/* Contact */}
              <td className="pr-3 pb-2">
                <Input
                  className="h-9"
                  value={att.contact}
                  onChange={(e) => updateAttendee(idx, "contact", e.target.value)}
                  placeholder="Contact"
                />
              </td>

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

export default AttendeesStep;