"use client";

import { useMemo, useState } from "react";
import type { MarketingRole, Meeting } from "@/lib/marketing";
import { formatDateTime, getStatusPillClass, MARKETING_ROLE_LABELS, MEETING_STATUS_LABELS } from "@/lib/marketing/labels";

type MeetingRequestInput = {
  title: string;
  agenda: string;
  suggestedTimes: string[];
  participantNames: string[];
};

type MeetingScheduleInput = {
  title: string;
  agenda: string;
  scheduledFor: string;
  participantNames: string[];
};

type MeetingCompletionInput = {
  meetingId: string;
  commitments: Array<{
    title: string;
    description?: string;
    ownerName?: string;
    dueDate?: string;
  }>;
};

type MeetingsWidgetProps = {
  meetings: Meeting[];
  role: MarketingRole;
  participantOptions?: string[];
  isSaving?: boolean;
  departmentLabel?: string;
  leadTitle?: string;
  onRequestMeeting: (input: MeetingRequestInput) => Promise<void>;
  onScheduleMeeting: (input: MeetingScheduleInput) => Promise<void>;
  onCompleteMeeting: (input: MeetingCompletionInput) => Promise<void>;
};

type RequestAudience = "lead" | "owner" | "person" | "team";
type ScheduleAudience = "owner" | "person" | "team" | "custom";

function participantLabel(meeting: Meeting): string {
  if (meeting.participantNames.length === 0) {
    return "Sin participantes";
  }

  if (meeting.participantNames.length <= 2) {
    return meeting.participantNames.join(" + ");
  }

  return `${meeting.participantNames.slice(0, 2).join(" + ")} +${meeting.participantNames.length - 2}`;
}

function toIsoFromLocal(localDateTime: string): string {
  return new Date(localDateTime).toISOString();
}

function normalizeParticipantNames(values: string[]): string[] {
  return Array.from(new Set(values.map((value) => value.trim()).filter((value) => value.length > 0)));
}

function toggleParticipant(list: string[], value: string): string[] {
  if (list.includes(value)) {
    return list.filter((entry) => entry !== value);
  }

  return [...list, value];
}

function requestAudienceLabel(value: RequestAudience): string {
  if (value === "lead") {
    return "Con líder";
  }

  if (value === "owner") {
    return "Con dueño";
  }

  if (value === "person") {
    return "1:1 con persona";
  }

  return "Con equipo";
}

function scheduleAudienceLabel(value: ScheduleAudience): string {
  if (value === "owner") {
    return "Con dueño";
  }

  if (value === "person") {
    return "1:1 con persona";
  }

  if (value === "team") {
    return "Con equipo";
  }

  return "Personalizada";
}

export default function MeetingsWidget({
  meetings,
  role,
  participantOptions = [],
  isSaving = false,
  departmentLabel = "Marketing",
  leadTitle = "Lider de Marketing",
  onRequestMeeting,
  onScheduleMeeting,
  onCompleteMeeting,
}: MeetingsWidgetProps) {
  const [requestTitle, setRequestTitle] = useState("Solicitud de reunión");
  const [requestAgenda, setRequestAgenda] = useState("");
  const [suggested1, setSuggested1] = useState("");
  const [suggested2, setSuggested2] = useState("");
  const [suggested3, setSuggested3] = useState("");
  const [requestAudience, setRequestAudience] = useState<RequestAudience>("lead");
  const [requestPerson, setRequestPerson] = useState("");
  const [requestTeam, setRequestTeam] = useState<string[]>([]);

  const [scheduleTitle, setScheduleTitle] = useState(`Revisión semanal ${departmentLabel}`);
  const [scheduleAgenda, setScheduleAgenda] = useState("");
  const [scheduleDateTime, setScheduleDateTime] = useState("");
  const [scheduleAudience, setScheduleAudience] = useState<ScheduleAudience>("owner");
  const [schedulePerson, setSchedulePerson] = useState("");
  const [scheduleTeam, setScheduleTeam] = useState<string[]>([]);
  const [scheduleParticipants, setScheduleParticipants] = useState(`Dueño, ${leadTitle}`);

  const [completionDraftByMeeting, setCompletionDraftByMeeting] = useState<Record<string, string>>({});

  const selectablePeople = useMemo(
    () => normalizeParticipantNames(participantOptions).filter((name) => name !== "Dueño"),
    [participantOptions]
  );

  const now = new Date().getTime();
  const upcoming = useMemo(
    () =>
      meetings
        .filter((meeting) => meeting.status !== "completed" && meeting.status !== "cancelled")
        .sort(
          (a, b) =>
            new Date(a.scheduledFor ?? a.suggestedTimes[0] ?? 0).getTime() -
            new Date(b.scheduledFor ?? b.suggestedTimes[0] ?? 0).getTime()
        ),
    [meetings]
  );
  const past = useMemo(
    () =>
      meetings
        .filter(
          (meeting) => meeting.status === "completed" || (meeting.scheduledFor ? new Date(meeting.scheduledFor).getTime() < now : false)
        )
        .sort((a, b) => new Date(b.completedAt ?? b.scheduledFor ?? 0).getTime() - new Date(a.completedAt ?? a.scheduledFor ?? 0).getTime()),
    [meetings, now]
  );

  const isLeadOrOwner = role === "lead" || role === "owner";
  const isEmployee = role === "employee";

  return (
    <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
      <div className="mb-4 flex flex-wrap items-end justify-between gap-2">
        <div>
          <h2 className="text-h2 font-semibold">Meetings</h2>
          <p className="text-label mt-1 text-benell-text-soft">{MARKETING_ROLE_LABELS[role]} · agenda de equipo y dirección.</p>
        </div>
      </div>

      {isEmployee ? (
        <div className="mb-4 rounded-xl border border-benell-stroke bg-white p-3">
          <p className="text-label font-semibold text-benell-text-soft">Solicitar reunión</p>
          <div className="mt-2 grid gap-2">
            <input
              type="text"
              value={requestTitle}
              onChange={(event) => setRequestTitle(event.target.value)}
              className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
              placeholder="Título"
            />
            <textarea
              rows={2}
              value={requestAgenda}
              onChange={(event) => setRequestAgenda(event.target.value)}
              className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
              placeholder="Agenda"
            />
            <select
              value={requestAudience}
              onChange={(event) => setRequestAudience(event.target.value as RequestAudience)}
              className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
            >
              {(["lead", "owner", "person", "team"] as RequestAudience[]).map((audience) => (
                <option key={audience} value={audience}>
                  {requestAudienceLabel(audience)}
                </option>
              ))}
            </select>

            {requestAudience === "person" ? (
              <select
                value={requestPerson}
                onChange={(event) => setRequestPerson(event.target.value)}
                className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
              >
                <option value="">Selecciona persona</option>
                {selectablePeople.map((name) => (
                  <option key={name} value={name}>
                    {name}
                  </option>
                ))}
              </select>
            ) : null}

            {requestAudience === "team" ? (
              <div className="rounded-xl border border-benell-stroke bg-benell-surface p-2">
                <p className="text-label mb-2 text-benell-text-soft">Selecciona equipo</p>
                <div className="grid gap-2 sm:grid-cols-2">
                  {selectablePeople.map((name) => (
                    <label key={name} className="inline-flex items-center gap-2 rounded-xl border border-benell-stroke bg-white p-2">
                      <input
                        type="checkbox"
                        checked={requestTeam.includes(name)}
                        onChange={() => setRequestTeam((prev) => toggleParticipant(prev, name))}
                      />
                      <span className="text-label">{name}</span>
                    </label>
                  ))}
                </div>
              </div>
            ) : null}

            <div className="grid gap-2 sm:grid-cols-3">
              <input type="datetime-local" value={suggested1} onChange={(event) => setSuggested1(event.target.value)} className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2" />
              <input type="datetime-local" value={suggested2} onChange={(event) => setSuggested2(event.target.value)} className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2" />
              <input type="datetime-local" value={suggested3} onChange={(event) => setSuggested3(event.target.value)} className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2" />
            </div>
            <button
              type="button"
              disabled={isSaving}
              onClick={async () => {
                const suggested = [suggested1, suggested2, suggested3].filter(Boolean);
                if (!requestAgenda.trim() || suggested.length === 0) {
                  return;
                }

                const participants = (() => {
                  if (requestAudience === "lead") {
                    return [leadTitle];
                  }

                  if (requestAudience === "owner") {
                    return ["Dueño", leadTitle];
                  }

                  if (requestAudience === "person") {
                    return requestPerson ? [requestPerson] : [];
                  }

                  return requestTeam;
                })();

                const participantNames = normalizeParticipantNames(participants);
                if (participantNames.length === 0) {
                  return;
                }

                await onRequestMeeting({
                  title: requestTitle.trim() || "Solicitud de reunión",
                  agenda: requestAgenda.trim(),
                  suggestedTimes: suggested.map(toIsoFromLocal),
                  participantNames,
                });

                setRequestAgenda("");
                setSuggested1("");
                setSuggested2("");
                setSuggested3("");
              }}
              className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-60"
            >
              Enviar solicitud
            </button>
          </div>
        </div>
      ) : null}

      {isLeadOrOwner ? (
        <div className="mb-4 rounded-xl border border-benell-stroke bg-white p-3">
          <p className="text-label font-semibold text-benell-text-soft">Programar reunión</p>
          <div className="mt-2 grid gap-2">
            <input
              type="text"
              value={scheduleTitle}
              onChange={(event) => setScheduleTitle(event.target.value)}
              className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
              placeholder="Título"
            />
            <textarea
              rows={2}
              value={scheduleAgenda}
              onChange={(event) => setScheduleAgenda(event.target.value)}
              className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
              placeholder="Agenda"
            />
            <input
              type="datetime-local"
              value={scheduleDateTime}
              onChange={(event) => setScheduleDateTime(event.target.value)}
              className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
            />
            <select
              value={scheduleAudience}
              onChange={(event) => setScheduleAudience(event.target.value as ScheduleAudience)}
              className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
            >
              {(["owner", "person", "team", "custom"] as ScheduleAudience[]).map((audience) => (
                <option key={audience} value={audience}>
                  {scheduleAudienceLabel(audience)}
                </option>
              ))}
            </select>

            {scheduleAudience === "person" ? (
              <select
                value={schedulePerson}
                onChange={(event) => setSchedulePerson(event.target.value)}
                className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
              >
                <option value="">Selecciona persona</option>
                {selectablePeople.map((name) => (
                  <option key={name} value={name}>
                    {name}
                  </option>
                ))}
              </select>
            ) : null}

            {scheduleAudience === "team" ? (
              <div className="rounded-xl border border-benell-stroke bg-benell-surface p-2">
                <p className="text-label mb-2 text-benell-text-soft">Selecciona equipo</p>
                <div className="grid gap-2 sm:grid-cols-2">
                  {selectablePeople.map((name) => (
                    <label key={name} className="inline-flex items-center gap-2 rounded-xl border border-benell-stroke bg-white p-2">
                      <input
                        type="checkbox"
                        checked={scheduleTeam.includes(name)}
                        onChange={() => setScheduleTeam((prev) => toggleParticipant(prev, name))}
                      />
                      <span className="text-label">{name}</span>
                    </label>
                  ))}
                </div>
              </div>
            ) : null}

            {scheduleAudience === "custom" ? (
              <input
                type="text"
                value={scheduleParticipants}
                onChange={(event) => setScheduleParticipants(event.target.value)}
                className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
                placeholder="Participantes separados por coma"
              />
            ) : null}

            <button
              type="button"
              disabled={isSaving}
              onClick={async () => {
                if (!scheduleAgenda.trim() || !scheduleDateTime) {
                  return;
                }

                const participants = (() => {
                  if (scheduleAudience === "owner") {
                    return role === "owner" ? ["Dueño"] : ["Dueño", leadTitle];
                  }

                  if (scheduleAudience === "person") {
                    return schedulePerson ? [schedulePerson] : [];
                  }

                  if (scheduleAudience === "team") {
                    return scheduleTeam;
                  }

                  return scheduleParticipants.split(",").map((value) => value.trim());
                })();

                const participantNames = normalizeParticipantNames(participants);
                if (participantNames.length === 0) {
                  return;
                }

                await onScheduleMeeting({
                  title: scheduleTitle.trim() || `Reunión ${departmentLabel}`,
                  agenda: scheduleAgenda.trim(),
                  scheduledFor: toIsoFromLocal(scheduleDateTime),
                  participantNames,
                });

                setScheduleAgenda("");
                setScheduleDateTime("");
              }}
              className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-60"
            >
              Agendar
            </button>
          </div>
        </div>
      ) : null}

      <div className="grid gap-3 lg:grid-cols-2">
        <div className="rounded-xl border border-benell-stroke bg-white p-4">
          <h3 className="text-h3 font-semibold">Próximas</h3>
          <div className="mt-3 space-y-2">
            {upcoming.length > 0 ? (
              upcoming.map((meeting) => {
                const completionDraft = completionDraftByMeeting[meeting.id] ?? "";

                return (
                  <article key={meeting.id} className="rounded-xl border border-benell-stroke bg-benell-surface p-3">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <p className="text-body font-semibold">{meeting.title}</p>
                      <span className={`rounded-pill px-2 py-1 text-label font-semibold ${getStatusPillClass(meeting.status)}`}>
                        {MEETING_STATUS_LABELS[meeting.status]}
                      </span>
                    </div>
                    <p className="text-label mt-1 text-benell-text-soft">{meeting.agenda}</p>
                    <p className="text-label mt-1 text-benell-text-soft">{participantLabel(meeting)}</p>
                    <p className="text-label mt-1 text-benell-text-soft">
                      {meeting.scheduledFor ? `Fecha: ${formatDateTime(meeting.scheduledFor)}` : "Sin fecha confirmada"}
                    </p>

                    {isLeadOrOwner && meeting.status === "scheduled" ? (
                      <div className="mt-2 space-y-2">
                        <textarea
                          rows={2}
                          value={completionDraft}
                          onChange={(event) =>
                            setCompletionDraftByMeeting((prev) => ({
                              ...prev,
                              [meeting.id]: event.target.value,
                            }))
                          }
                          className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                          placeholder="Compromisos (uno por línea)"
                        />
                        <button
                          type="button"
                          disabled={isSaving}
                          onClick={async () => {
                            const lines = completionDraft
                              .split("\n")
                              .map((line) => line.trim())
                              .filter(Boolean);
                            if (lines.length === 0) {
                              return;
                            }

                            await onCompleteMeeting({
                              meetingId: meeting.id,
                              commitments: lines.map((title) => ({ title })),
                            });

                            setCompletionDraftByMeeting((prev) => ({
                              ...prev,
                              [meeting.id]: "",
                            }));
                          }}
                          className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-60"
                        >
                          Completar y generar compromisos
                        </button>
                      </div>
                    ) : null}
                  </article>
                );
              })
            ) : (
              <p className="text-label text-benell-text-soft">No hay reuniones próximas.</p>
            )}
          </div>
        </div>

        <div className="rounded-xl border border-benell-stroke bg-white p-4">
          <h3 className="text-h3 font-semibold">Historial</h3>
          <div className="mt-3 space-y-2">
            {past.length > 0 ? (
              past.map((meeting) => (
                <article key={meeting.id} className="rounded-xl border border-benell-stroke bg-benell-surface p-3">
                  <div className="flex flex-wrap items-start justify-between gap-2">
                    <p className="text-body font-semibold">{meeting.title}</p>
                    <span className={`rounded-pill px-2 py-1 text-label font-semibold ${getStatusPillClass(meeting.status)}`}>
                      {MEETING_STATUS_LABELS[meeting.status]}
                    </span>
                  </div>
                  <p className="text-label mt-1 text-benell-text-soft">{meeting.agenda}</p>
                  <p className="text-label mt-1 text-benell-text-soft">Compromisos: {meeting.commitments.length}</p>
                  <p className="text-label mt-1 text-benell-text-soft">Cierre: {formatDateTime(meeting.completedAt ?? meeting.scheduledFor)}</p>
                </article>
              ))
            ) : (
              <p className="text-label text-benell-text-soft">Aún no hay reuniones cerradas.</p>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
