"use client";

import React from "react";
import { Input, Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "ikoncomponents";
import { AgendaData, AgendaItem, Attendee, ApiUser } from "../../types";
import { StepErrors } from "../../lib/validation";

interface AgendaStepProps {
  data: AgendaData;
  onChange: (field: keyof AgendaData, value: AgendaItem[]) => void;
  attendees: Attendee[];
  users: ApiUser[];
  errors: StepErrors;
}

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

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

const AgendaStep: React.FC<AgendaStepProps> = ({ data, onChange, attendees, users, errors }) => {
  const addItem = () => onChange("agenda", [...data.agenda, { item: "", owner: "" }]);

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

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

  const presenterOptions = attendees
    .filter((a) => a.name)
    .map((a) => {
      const user = users.find((u) => u.userId === a.name);
      return { value: a.name, label: user?.userName ?? a.name };
    });

  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-3">
              Owner / Presenter <span className="text-destructive">*</span>
            </th>
            <th className="pb-2 w-[40px] text-right">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={addItem}
                className="text-emerald-600   text-xs px-2 py-1"
              >
                + ADD
              </Button>
            </th>
          </tr>
        </thead>

        <tbody>
          {data.agenda.map((ag, 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>

              <td className="pr-8 pb-2">
                <Input
                  value={ag.item}
                  onChange={(e) => updateItem(idx, "item", e.target.value)}
                  placeholder="Agenda item"
                  className={rowError(errors, idx, "item") ? "border-destructive" : ""}
                />
                <FieldError message={rowError(errors, idx, "item")} />
              </td>

              <td className="pr-3 pb-2">
                <Select
                  value={ag.owner}
                  onValueChange={(v) => updateItem(idx, "owner", v)}
                  disabled={presenterOptions.length === 0}
                >
                  <SelectTrigger className={rowError(errors, idx, "owner") ? "border-destructive" : ""}>
                    <SelectValue
                      placeholder={
                        presenterOptions.length === 0 ? "No attendees selected yet" : "Select Presenter Name"
                      }
                    />
                  </SelectTrigger>
                  <SelectContent side="bottom" position="popper" sideOffset={4} className="max-h-52 overflow-y-auto">
                    {presenterOptions.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError message={rowError(errors, idx, "owner")} />
              </td>

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

      {presenterOptions.length === 0 && (
        <p className="text-xs text-muted-foreground text-center py-1">
          ⚠️ Go to the Attendees step and select attendees first to populate the Owner/Presenter dropdown.
        </p>
      )}
    </div>
  );
};

export default AgendaStep;