"use client";

import React, { useEffect, useState } from "react";
import { Input, Label, Textarea, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "ikoncomponents";
import { DURATION_UNIT_OPTIONS } from "../../lib/utils";
import { MeetingData, ApiUser } from "../../types";
import { StepErrors } from "../../lib/validation";
import { getUsersApi } from "@/app/utils/api/projectApi";

interface MeetingStepProps {
  data: MeetingData;
  onChange: (field: keyof MeetingData, value: string) => void;
  errors: StepErrors;
}

// Small helper to render an error message under a field
const FieldError = ({ message }: { message?: string }) =>
  message ? <p className="text-xs text-destructive mt-1">{message}</p> : null;

const MeetingStep: React.FC<MeetingStepProps> = ({ data, onChange, errors }) => {
  const [users, setUsers] = useState<ApiUser[]>([]);
  const [loadingUsers, setLoadingUsers] = useState(false);

  useEffect(() => {
    const fetchUsers = async () => {
      setLoadingUsers(true);
      try {
        const result: ApiUser[] = await getUsersApi();
        setUsers(result.filter((u) => u.active && !u.userDeleted));
      } catch (error) {
        console.error("Failed to fetch users:", error);
      } finally {
        setLoadingUsers(false);
      }
    };
    fetchUsers();
  }, []);

  return (
    <div className="space-y-4">
      {/* Title / Objective */}
      <div className="space-y-1.5">
        <Label htmlFor="title">
          Title / Objective <span className="text-destructive">*</span>
        </Label>
        <Input
          id="title"
          value={data.title}
          onChange={(e) => onChange("title", e.target.value)}
          placeholder="Meeting title or objective"
          className={errors.title ? "border-destructive" : ""}
        />
        <FieldError message={errors.title} />
      </div>

      {/* Project Name + Place */}
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-1.5">
          <Label htmlFor="projectName">
            Project Name <span className="text-destructive">*</span>
          </Label>
          <Input
            id="projectName"
            value={data.projectName}
            onChange={(e) => onChange("projectName", e.target.value)}
            placeholder="Project name"
            className={errors.projectName ? "border-destructive" : ""}
          />
          <FieldError message={errors.projectName} />
        </div>

        <div className="space-y-1.5">
          <Label htmlFor="place">
            Place <span className="text-destructive">*</span>
          </Label>
          <Input
            id="place"
            value={data.place}
            onChange={(e) => onChange("place", e.target.value)}
            placeholder="Enter location"
            className={errors.place ? "border-destructive" : ""}
          />
          <FieldError message={errors.place} />
        </div>
      </div>

      {/* Date + Time + Duration */}
      <div className="grid grid-cols-3 gap-4">
        <div className="space-y-1.5">
          <Label htmlFor="date">
            Date <span className="text-destructive">*</span>
          </Label>
          <Input
            id="date"
            type="date"
            value={data.date}
            onChange={(e) => onChange("date", e.target.value)}
            className={errors.date ? "border-destructive" : ""}
          />
          <FieldError message={errors.date} />
        </div>

        <div className="space-y-1.5">
          <Label htmlFor="time">
            Time <span className="text-destructive">*</span>
          </Label>
          <Input
            id="time"
            type="time"
            value={data.time}
            onChange={(e) => onChange("time", e.target.value)}
            className={errors.time ? "border-destructive" : ""}
          />
          <FieldError message={errors.time} />
        </div>

        <div className="space-y-1.5">
          <Label>
            Duration <span className="text-destructive">*</span>
          </Label>
          <div className="flex gap-2">
            <div className="flex flex-col">
              <Input
                type="number"
                placeholder="0"
                value={data.duration}
                onChange={(e) => onChange("duration", e.target.value)}
                className={`w-20 ${errors.duration ? "border-destructive" : ""}`}
              />
              <FieldError message={errors.duration} />
            </div>
            <div className="flex flex-col flex-1">
              <Select
                value={data.durationUnit}
                onValueChange={(v) => onChange("durationUnit", v)}
              >
                <SelectTrigger className={`flex-1 ${errors.durationUnit ? "border-destructive" : ""}`}>
                  <SelectValue placeholder="Unit" />
                </SelectTrigger>
                <SelectContent>
                  {DURATION_UNIT_OPTIONS.map((opt) => (
                    <SelectItem key={opt.value} value={opt.value}>
                      {opt.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FieldError message={errors.durationUnit} />
            </div>
          </div>
        </div>
      </div>

      {/* Called By */}
      <div className="space-y-1.5">
        <Label>
          Called By <span className="text-destructive">*</span>
        </Label>
        <Select
          value={data.calledBy || ""}
          onValueChange={(v) => onChange("calledBy", v)}
          disabled={loadingUsers}
        >
          <SelectTrigger className={`w-full ${errors.calledBy ? "border-destructive" : ""}`}>
            <SelectValue
              placeholder={
                loadingUsers
                  ? "Loading users..."
                  : users.length === 0
                  ? "No users found"
                  : "Select Called By"
              }
            />
          </SelectTrigger>
          <SelectContent className="w-full max-h-60 overflow-y-auto">
            {users.length === 0 && !loadingUsers && (
              <div className="px-2 py-1 text-sm text-muted-foreground">
                No active users available
              </div>
            )}
            {users.map((user) => (
              <SelectItem key={user.userId} value={String(user.userId)} className="truncate">
                {user.userName}
                {user.userDesignation ? ` (${user.userDesignation})` : ""}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <FieldError message={errors.calledBy} />
      </div>
    </div>
  );
};

export default MeetingStep;