import React, { useMemo, useState } from "react";
import styled from "styled-components";
import {
  FiltersRow,
  FilterGroup,
  FilterLabel,
  FilterSelect,
} from "../styles";
import KpiCascadeFilter, { kpiMatchesCascadeSteps } from "../../../DataManagment/Quantative/component/KpiTagFilter";
import { PERIOD_TYPE_LABELS, formatDateRange } from "../hooks/useTriggers";

// ─── Styles ───────────────────────────────────────────────────────────────────
const Wrapper = styled.div``;

const TableWrapper = styled.div`
  margin-top: 24px;
  border: 1.5px solid #e2e8f0;
  border-radius: 12px;
  overflow: hidden;
  overflow-x: auto;
`;

const Table = styled.table`
  width: 100%;
  min-width: 760px;
  border-collapse: collapse;
  font-size: 13px;
`;

const Thead = styled.thead`
  background: #f8fafc;
`;

const Th = styled.th`
  padding: 10px 14px;
  text-align: left;
  font-size: 11px;
  font-weight: 700;
  color: #64748b;
  text-transform: uppercase;
  letter-spacing: 0.4px;
  border-bottom: 1.5px solid #e2e8f0;
  white-space: nowrap;
`;

const Tr = styled.tr`
  &:not(:last-child) td {
    border-bottom: 1px solid #f1f5f9;
  }
  &:hover td {
    background: #f8fafc;
  }
`;

const Td = styled.td`
  padding: 10px 14px;
  color: #1e293b;
  vertical-align: top;
`;

const EmailPill = styled.span`
  display: inline-block;
  padding: 2px 8px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 500;
  background: #e0f2fe;
  color: #0369a1;
  margin: 2px 3px 2px 0;
  white-space: nowrap;
`;

const PeriodBadge = styled.span`
  display: inline-block;
  padding: 2px 8px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 600;
  background: #e0f2fe;
  color: #0369a1;
`;

const EmptyState = styled.div`
  padding: 48px 0;
  text-align: center;
  color: #94a3b8;
  font-size: 14px;
`;

const EmptyCell = styled.span`
  color: #cbd5e1;
  font-size: 13px;
`;

const MoreBadge = styled.button`
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 700;
  background: #3f88a5;
  color: #fff;
  border: none;
  cursor: pointer;
  margin: 2px 0 2px 2px;
  white-space: nowrap;
  transition: background 0.15s;
  &:hover { background: #2e6d88; }
`;

const PillRow = styled.div`
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 2px;
  white-space: nowrap;
`;

// Shows up to maxVisible pills, then a clickable "+N" badge.
const EmailPillCell = ({ list, onShowMore, label }) => {
  if (!list || list.length === 0) return <EmptyCell>—</EmptyCell>;
  const maxVisible = 1;
  const visible = list.slice(0, maxVisible);
  const hidden  = list.length - maxVisible;
  return (
    <PillRow>
      {visible.map((email) => <EmailPill key={email}>{email}</EmailPill>)}
      {hidden > 0 && (
        <MoreBadge type="button" onClick={() => onShowMore(label)}>
          +{hidden}
        </MoreBadge>
      )}
    </PillRow>
  );
};

// ─── Modal ────────────────────────────────────────────────────────────────────
const ModalBackdrop = styled.div`
  position: fixed;
  inset: 0;
  background: rgba(15, 23, 42, 0.35);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
`;

const ModalCard = styled.div`
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(15, 23, 42, 0.18);
  padding: 28px 28px 24px;
  min-width: 340px;
  max-width: 520px;
  width: 90%;
  max-height: 70vh;
  overflow-y: auto;
`;

const ModalHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18px;
`;

const ModalTitle = styled.h3`
  font-size: 14px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
`;

const CloseBtn = styled.button`
  background: none;
  border: none;
  font-size: 18px;
  color: #64748b;
  cursor: pointer;
  line-height: 1;
  padding: 2px 4px;
  border-radius: 6px;
  &:hover { background: #f1f5f9; color: #1e293b; }
`;

const ModalSection = styled.div`
  margin-bottom: 14px;
  &:last-child { margin-bottom: 0; }
`;

const ModalSectionLabel = styled.p`
  font-size: 10px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: #94a3b8;
  margin: 0 0 6px;
`;

const ModalPillWrap = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
`;

const RecipientsModal = ({ trigger, highlightField, onClose }) => {
  if (!trigger) return null;
  const { to = [], cc = [], bcc = [] } = trigger.emailRecipients ?? {};
  const sections = [
    { label: "To",  emails: to },
    { label: "CC",  emails: cc },
    { label: "BCC", emails: bcc },
  ].filter(s => s.emails.length > 0);

  return (
    <ModalBackdrop onClick={onClose}>
      <ModalCard onClick={(e) => e.stopPropagation()}>
        <ModalHeader>
          <ModalTitle>Email Recipients</ModalTitle>
          <CloseBtn onClick={onClose}>×</CloseBtn>
        </ModalHeader>
        {sections.map(({ label, emails }) => (
          <ModalSection key={label}>
            <ModalSectionLabel>{label}</ModalSectionLabel>
            <ModalPillWrap>
              {emails.map((email) => (
                <EmailPill
                  key={email}
                  style={highlightField === label
                    ? { background: "#dbeafe", color: "#1d4ed8" }
                    : undefined}
                >
                  {email}
                </EmailPill>
              ))}
            </ModalPillWrap>
          </ModalSection>
        ))}
      </ModalCard>
    </ModalBackdrop>
  );
};

// ─── Component ────────────────────────────────────────────────────────────────
const EmailOverviewTab = ({ hook }) => {
  const {
    sources,
    triggers,
    questions,
    selectedFinancialYear,
    eovw_periodType, setEovw_periodType,
    eovw_selectedPeriod, setEovw_selectedPeriod,
    eovw_sourceId, setEovw_sourceId,
    computePeriodSlots,
  } = hook;

  const [filterSteps, setFilterSteps] = useState([]);

  // All triggers with email recipients for the selected FY.
  const fyTriggers = useMemo(
    () => triggers.filter(
      (t) =>
        String(t.financialYearId) === String(selectedFinancialYear) &&
        t.emailRecipients != null
    ),
    [triggers, selectedFinancialYear]
  );

  const availablePeriodTypes = useMemo(() => {
    const types = ["YEARLY", "HALF_YEARLY", "QUARTERLY", "MONTHLY"];
    return types.filter((type) => {
      const slots = computePeriodSlots(type);
      return slots.some((slot) =>
        fyTriggers.some((t) => t.fromDate === slot.fromDate && t.toDate === slot.toDate)
      );
    });
  }, [fyTriggers, computePeriodSlots]);

  const availablePeriodSlots = useMemo(() => {
    if (!eovw_periodType) return [];
    const slots = computePeriodSlots(eovw_periodType);
    return slots.filter((slot) =>
      fyTriggers.some((t) => t.fromDate === slot.fromDate && t.toDate === slot.toDate)
    );
  }, [eovw_periodType, fyTriggers, computePeriodSlots]);

  const availableSources = useMemo(() => {
    let pool = fyTriggers;
    if (eovw_selectedPeriod) {
      pool = pool.filter((t) =>
        t.fromDate === eovw_selectedPeriod.fromDate && t.toDate === eovw_selectedPeriod.toDate
      );
    } else if (eovw_periodType) {
      const slotKeys = new Set(availablePeriodSlots.map((s) => `${s.fromDate}|${s.toDate}`));
      pool = pool.filter((t) => slotKeys.has(`${t.fromDate}|${t.toDate}`));
    }
    const ids = [...new Set(pool.map((t) => t.sourceId))];
    return sources.filter((s) => ids.includes(s.id));
  }, [fyTriggers, eovw_selectedPeriod, eovw_periodType, availablePeriodSlots, sources]);

  const kpiListForFilter = useMemo(
    () => questions.map((q) => ({ ...q, id: q.questionId, rawTags: q.tags })),
    [questions]
  );

  const filteredTriggers = useMemo(() => {
    if (!selectedFinancialYear) return [];
    let result = fyTriggers;
    if (eovw_periodType) {
      const slotKeys = new Set(availablePeriodSlots.map((s) => `${s.fromDate}|${s.toDate}`));
      result = result.filter((t) => slotKeys.has(`${t.fromDate}|${t.toDate}`));
    }
    if (eovw_selectedPeriod) {
      result = result.filter((t) =>
        t.fromDate === eovw_selectedPeriod.fromDate && t.toDate === eovw_selectedPeriod.toDate
      );
    }
    if (eovw_sourceId) {
      result = result.filter((t) => t.sourceId === eovw_sourceId);
    }
    const active = filterSteps.filter((s) => s.values?.size);
    if (active.length > 0) {
      result = result.filter((t) => {
        const q = kpiListForFilter.find((q) => q.questionId === t.questionId);
        return q ? kpiMatchesCascadeSteps(q, filterSteps) : false;
      });
    }
    return result;
  }, [fyTriggers, selectedFinancialYear, eovw_periodType, eovw_selectedPeriod, eovw_sourceId, availablePeriodSlots, filterSteps, kpiListForFilter]);

  const handlePeriodTypeChange = (e) => {
    setEovw_periodType(e.target.value);
    setEovw_selectedPeriod(null);
  };

  const handlePeriodSlotChange = (e) => {
    const slot = availablePeriodSlots.find((s) => s.fromDate === e.target.value);
    setEovw_selectedPeriod(slot ?? null);
  };

  const handleSourceChange = (e) => {
    setEovw_sourceId(e.target.value ? Number(e.target.value) : null);
  };

  const getSourceLabel = (id) => sources.find((s) => s.id === id)?.unitCode ?? id;

  // ── Modal state ───────────────────────────────────────────────────────────
  const [modalTrigger, setModalTrigger]     = useState(null);
  const [highlightField, setHighlightField] = useState(null);

  const openModal  = (trigger, field) => { setModalTrigger(trigger); setHighlightField(field); };
  const closeModal = ()               => { setModalTrigger(null);    setHighlightField(null);  };

  return (
    <>
      <Wrapper>
      <FiltersRow>
        {/* Period Type */}
        <FilterGroup>
          <FilterLabel>Period Type</FilterLabel>
          <FilterSelect
            value={eovw_periodType}
            onChange={handlePeriodTypeChange}
            disabled={!selectedFinancialYear}
          >
            <option value="">All types</option>
            {availablePeriodTypes.map((type) => (
              <option key={type} value={type}>{PERIOD_TYPE_LABELS[type]}</option>
            ))}
          </FilterSelect>
        </FilterGroup>

        {/* Period Slot */}
        <FilterGroup>
          <FilterLabel>Period</FilterLabel>
          <FilterSelect
            value={eovw_selectedPeriod?.fromDate ?? ""}
            onChange={handlePeriodSlotChange}
            disabled={!eovw_periodType}
          >
            <option value="">All periods</option>
            {availablePeriodSlots.map((slot) => (
              <option key={slot.fromDate} value={slot.fromDate}>{slot.label}</option>
            ))}
          </FilterSelect>
        </FilterGroup>

        {/* Location */}
        <FilterGroup>
          <FilterLabel>Location</FilterLabel>
          <FilterSelect
            value={eovw_sourceId ?? ""}
            onChange={handleSourceChange}
            disabled={!selectedFinancialYear}
          >
            <option value="">All locations</option>
            {availableSources.map((s) => (
              <option key={s.id} value={s.id}>{s.unitCode}</option>
            ))}
          </FilterSelect>
        </FilterGroup>

        {/* KPI Tags */}
        <FilterGroup style={{ flex: "1 1 260px", minWidth: 200 }}>
          <FilterLabel>KPI Tags (optional)</FilterLabel>
          <KpiCascadeFilter
            kpiList={kpiListForFilter}
            filterSteps={filterSteps}
            onFilterStepsChange={setFilterSteps}
          />
        </FilterGroup>
      </FiltersRow>

      {/* Results table */}
      {selectedFinancialYear ? (
        <TableWrapper>
          <Table>
            <Thead>
              <tr>
                <Th>Period</Th>
                <Th>Location</Th>
                <Th>KPI</Th>
                <Th>To</Th>
                <Th>CC</Th>
                <Th>BCC</Th>
              </tr>
            </Thead>
            <tbody>
              {filteredTriggers.length === 0 ? (
                <tr>
                  <td colSpan={6}>
                    <EmptyState>No triggers found for the selected filters.</EmptyState>
                  </td>
                </tr>
              ) : (
                filteredTriggers.map((t) => (
                  <Tr key={t.id}>
                    <Td>{formatDateRange(t.fromDate, t.toDate)}</Td>
                    <Td>{getSourceLabel(t.sourceId)}</Td>
                    <Td>{t.questionTitle}</Td>
                    <Td>
                      <EmailPillCell
                        list={t.emailRecipients?.to}
                        label="To"
                        onShowMore={(field) => openModal(t, field)}
                      />
                    </Td>
                    <Td>
                      <EmailPillCell
                        list={t.emailRecipients?.cc}
                        label="CC"
                        onShowMore={(field) => openModal(t, field)}
                      />
                    </Td>
                    <Td>
                      <EmailPillCell
                        list={t.emailRecipients?.bcc}
                        label="BCC"
                        onShowMore={(field) => openModal(t, field)}
                      />
                    </Td>
                  </Tr>
                ))
              )}
            </tbody>
          </Table>
        </TableWrapper>
      ) : (
        <EmptyState style={{ marginTop: 40 }}>
          Select a financial year to view email recipients.
        </EmptyState>
      )}
    </Wrapper>

    {modalTrigger && (
      <RecipientsModal
        trigger={modalTrigger}
        highlightField={highlightField}
        onClose={closeModal}
      />
    )}
  </>
  );
};

export default EmailOverviewTab;
