'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useMemo, useState } from 'react';

type Campaign = {
  id: string;
  code: string;
  name: string;
  audience: string;
  audienceGroup: string;
  sent: string;
  opened: string;
  status: 'Sent' | 'Scheduled' | 'Draft' | 'Failed';
  deliveryRate: number | null;
  dateLabel: string;
  timeLabel: string;
};

type Props = {
  labels: Record<string, string>;
  campaigns: Campaign[];
  metrics?: {
    totalMessages: number;
    averageDeliveryRate: number;
    scheduledCount: number;
    failedDeliveries: number;
  };
};

const STATUS_FILTERS = ['All Campaigns', 'Sent', 'Scheduled', 'Draft', 'Failed'] as const;
const SORT_OPTIONS = ['newest', 'oldest', 'delivery'] as const;

type StatusFilter = (typeof STATUS_FILTERS)[number];
type SortOption = (typeof SORT_OPTIONS)[number];

function parseCampaignDate(campaign: Campaign) {
  if (campaign.status === 'Scheduled') {
    return Number.POSITIVE_INFINITY;
  }

  if (campaign.dateLabel === 'Not set') {
    return Number.NEGATIVE_INFINITY;
  }

  const parsed = Date.parse(`${campaign.dateLabel} ${campaign.timeLabel}`.trim());
  return Number.isNaN(parsed) ? Number.NEGATIVE_INFINITY : parsed;
}

function formatCompactNumber(value: number) {
  return new Intl.NumberFormat('en', {
    notation: 'compact',
    maximumFractionDigits: 1,
  }).format(value);
}

function formatPercent(value: number) {
  return `${value.toFixed(1)}%`;
}

function getStatusClassName(status: Campaign['status']) {
  switch (status) {
    case 'Sent':
      return 'campaign-status-pill is-sent';
    case 'Scheduled':
      return 'campaign-status-pill is-scheduled';
    case 'Draft':
      return 'campaign-status-pill is-draft';
    case 'Failed':
      return 'campaign-status-pill is-failed';
  }
}

function getStatusLabel(status: Campaign['status'], labels: Record<string, string>) {
  switch (status) {
    case 'Sent':
      return labels.sent;
    case 'Scheduled':
      return labels.scheduled;
    case 'Draft':
      return labels.draft;
    case 'Failed':
      return labels.failed;
  }
}

function getFilterLabel(filter: StatusFilter, labels: Record<string, string>) {
  return filter === 'All Campaigns' ? labels.allCampaigns : getStatusLabel(filter, labels);
}

export function CampaignsManagementBoard({ labels, campaigns, metrics }: Props) {
  const router = useRouter();
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('All Campaigns');
  const [sortBy, setSortBy] = useState<SortOption>('newest');
  const [search, setSearch] = useState('');
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [createError, setCreateError] = useState('');
  const [createForm, setCreateForm] = useState({
    name: '',
    audienceLabel: '',
    audienceGroup: '',
    totalRecipients: '1000',
    status: 'Draft',
    scheduledAt: '',
    templateName: '',
    language: 'English (US)',
    messageTitle: '',
    messageBody: '',
    primaryButton: '',
    secondaryButton: '',
    bannerImageUrl: '',
  });

  const filteredCampaigns = useMemo(() => {
    const loweredSearch = search.trim().toLowerCase();

    const nextRows = campaigns.filter((campaign) => {
      const matchesStatus = statusFilter === 'All Campaigns' || campaign.status === statusFilter;
      const matchesSearch =
        loweredSearch.length === 0 ||
        campaign.name.toLowerCase().includes(loweredSearch) ||
        campaign.code.toLowerCase().includes(loweredSearch) ||
        campaign.audience.toLowerCase().includes(loweredSearch);

      return matchesStatus && matchesSearch;
    });

    nextRows.sort((left, right) => {
      if (sortBy === 'delivery') {
        return (right.deliveryRate ?? -1) - (left.deliveryRate ?? -1);
      }

      const leftDate = parseCampaignDate(left);
      const rightDate = parseCampaignDate(right);

      return sortBy === 'newest' ? rightDate - leftDate : leftDate - rightDate;
    });

    return nextRows;
  }, [campaigns, search, sortBy, statusFilter]);

  const computedMetrics = useMemo(() => {
    const totalSent = campaigns.reduce((sum, campaign) => sum + Number(campaign.sent.replace(/,/g, '')), 0);
    const deliveryRates = campaigns
      .map((campaign) => campaign.deliveryRate)
      .filter((rate): rate is number => rate !== null && rate > 0);
    const averageDeliveryRate = deliveryRates.length
      ? deliveryRates.reduce((sum, rate) => sum + rate, 0) / deliveryRates.length
      : 0;
    const scheduledCount = campaigns.filter((campaign) => campaign.status === 'Scheduled').length;
    const failedDeliveries = campaigns.reduce((sum, campaign) => {
      if (campaign.deliveryRate === null) {
        return sum;
      }

      const sent = Number(campaign.sent.replace(/,/g, ''));
      const failed = Math.round(sent * (1 - campaign.deliveryRate / 100));
      return sum + Math.max(failed, 0);
    }, 0);

    return {
      totalSent,
      averageDeliveryRate,
      scheduledCount,
      failedDeliveries,
    };
  }, [campaigns]);

  const resolvedMetrics = {
    totalMessages: metrics?.totalMessages ?? computedMetrics.totalSent,
    averageDeliveryRate: metrics?.averageDeliveryRate ?? computedMetrics.averageDeliveryRate,
    scheduledCount: metrics?.scheduledCount ?? computedMetrics.scheduledCount,
    failedDeliveries: metrics?.failedDeliveries ?? computedMetrics.failedDeliveries,
  };

  return (
    <div className="campaigns-page">
      <section className="campaigns-header">
        <div>
          <h1 className="campaigns-title">{labels.title}</h1>
          <p className="campaigns-copy">{labels.copy}</p>
        </div>
        <button type="button" className="campaigns-primary-button" onClick={() => setIsCreateOpen(true)}>
          <span className="material-symbols-outlined">campaign</span>
          {labels.newCampaign}
        </button>
      </section>

      {isCreateOpen ? (
        <section className="campaigns-create-modal-backdrop" onClick={() => !isCreating && setIsCreateOpen(false)}>
          <div className="campaigns-create-modal" onClick={(event) => event.stopPropagation()}>
            <div className="campaigns-create-modal-head">
              <div>
                <p>{labels.createCampaign}</p>
                <h2>{labels.launchBroadcast}</h2>
              </div>
              <button type="button" onClick={() => !isCreating && setIsCreateOpen(false)}>
                <span className="material-symbols-outlined">close</span>
              </button>
            </div>
            <form
              className="campaigns-create-form"
              onSubmit={async (event) => {
                event.preventDefault();
                setIsCreating(true);
                setCreateError('');

                try {
                  const response = await fetch('/api/campaigns', {
                    method: 'POST',
                    credentials: 'include',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                      ...createForm,
                      totalRecipients: Number(createForm.totalRecipients),
                    }),
                  });

                  const payload = await response.json();
                  if (!response.ok) {
                    throw new Error(typeof payload?.message === 'string' ? payload.message : labels.failedCreate);
                  }

                  setIsCreateOpen(false);
                  router.push(`/dashboard/campaigns/${payload.id}`);
                  router.refresh();
                } catch (error) {
                  setCreateError(error instanceof Error ? error.message : labels.failedCreate);
                } finally {
                  setIsCreating(false);
                }
              }}
            >
              <label>
                <span>{labels.campaignName}</span>
                <input
                  value={createForm.name}
                  onChange={(event) => setCreateForm((current) => ({ ...current, name: event.target.value }))}
                  placeholder={labels.namePlaceholder}
                  required
                />
              </label>
              <label>
                <span>{labels.audienceLabel}</span>
                <input
                  value={createForm.audienceLabel}
                  onChange={(event) => setCreateForm((current) => ({ ...current, audienceLabel: event.target.value }))}
                  placeholder={labels.audiencePlaceholder}
                  required
                />
              </label>
              <label>
                <span>{labels.audienceGroup}</span>
                <input
                  value={createForm.audienceGroup}
                  onChange={(event) => setCreateForm((current) => ({ ...current, audienceGroup: event.target.value }))}
                  placeholder={labels.groupPlaceholder}
                  required
                />
              </label>
              <label>
                <span>{labels.totalRecipients}</span>
                <input
                  type="number"
                  min="0"
                  value={createForm.totalRecipients}
                  onChange={(event) => setCreateForm((current) => ({ ...current, totalRecipients: event.target.value }))}
                  required
                />
              </label>
              <label>
                <span>{labels.status}</span>
                <select
                  value={createForm.status}
                  onChange={(event) => setCreateForm((current) => ({ ...current, status: event.target.value }))}
                >
                  <option value="Draft">{labels.draft}</option>
                  <option value="Scheduled">{labels.scheduled}</option>
                </select>
              </label>
              <label>
                <span>{labels.scheduledAt}</span>
                <input
                  type="datetime-local"
                  value={createForm.scheduledAt}
                  onChange={(event) => setCreateForm((current) => ({ ...current, scheduledAt: event.target.value }))}
                />
              </label>
              <label>
                <span>{labels.templateName}</span>
                <input
                  value={createForm.templateName}
                  onChange={(event) => setCreateForm((current) => ({ ...current, templateName: event.target.value }))}
                  placeholder={labels.templatePlaceholder}
                />
              </label>
              <label>
                <span>{labels.language}</span>
                <input
                  value={createForm.language}
                  onChange={(event) => setCreateForm((current) => ({ ...current, language: event.target.value }))}
                />
              </label>
              <label className="is-wide">
                <span>{labels.messageTitle}</span>
                <input
                  value={createForm.messageTitle}
                  onChange={(event) => setCreateForm((current) => ({ ...current, messageTitle: event.target.value }))}
                  placeholder={labels.titlePlaceholder}
                />
              </label>
              <label className="is-wide">
                <span>{labels.messageBody}</span>
                <textarea
                  value={createForm.messageBody}
                  onChange={(event) => setCreateForm((current) => ({ ...current, messageBody: event.target.value }))}
                  placeholder={labels.bodyPlaceholder}
                  rows={4}
                />
              </label>
              <label>
                <span>{labels.primaryButton}</span>
                <input
                  value={createForm.primaryButton}
                  onChange={(event) => setCreateForm((current) => ({ ...current, primaryButton: event.target.value }))}
                  placeholder={labels.primaryPlaceholder}
                />
              </label>
              <label>
                <span>{labels.secondaryButton}</span>
                <input
                  value={createForm.secondaryButton}
                  onChange={(event) => setCreateForm((current) => ({ ...current, secondaryButton: event.target.value }))}
                  placeholder={labels.secondaryPlaceholder}
                />
              </label>
              <label className="is-wide">
                <span>{labels.bannerImageUrl}</span>
                <input
                  value={createForm.bannerImageUrl}
                  onChange={(event) => setCreateForm((current) => ({ ...current, bannerImageUrl: event.target.value }))}
                  placeholder="https://..."
                />
              </label>

              {createError ? <p className="campaigns-create-error">{createError}</p> : null}

              <div className="campaigns-create-actions">
                <button type="button" className="campaigns-create-cancel" onClick={() => setIsCreateOpen(false)}>
                  {labels.cancel}
                </button>
                <button type="submit" className="campaigns-primary-button" disabled={isCreating}>
                  <span className="material-symbols-outlined">campaign</span>
                  {isCreating ? labels.creating : labels.createCampaign}
                </button>
              </div>
            </form>
          </div>
        </section>
      ) : null}

      <section className="campaigns-stats-grid">
        <article className="campaigns-stat-card">
          <div className="campaigns-stat-head">
            <span className="material-symbols-outlined">send</span>
            <span className="campaigns-stat-delta is-positive">
              <span className="material-symbols-outlined">trending_up</span>
              12%
            </span>
          </div>
          <div>
            <p>{labels.totalMessages}</p>
            <strong>{formatCompactNumber(resolvedMetrics.totalMessages)}</strong>
          </div>
        </article>

        <article className="campaigns-stat-card">
          <div className="campaigns-stat-head">
            <span className="material-symbols-outlined is-secondary">done_all</span>
            <span className="campaigns-stat-delta is-positive">
              <span className="material-symbols-outlined">trending_up</span>
              8.4%
            </span>
          </div>
          <div>
            <p>{labels.deliveryRate}</p>
            <strong className="is-secondary">{formatPercent(resolvedMetrics.averageDeliveryRate)}</strong>
          </div>
        </article>

        <article className="campaigns-stat-card">
          <div className="campaigns-stat-head">
            <span className="material-symbols-outlined is-warning">schedule</span>
          </div>
          <div>
            <p>{labels.scheduled}</p>
            <strong>{resolvedMetrics.scheduledCount}</strong>
          </div>
        </article>

        <article className="campaigns-stat-card">
          <div className="campaigns-stat-head">
            <span className="material-symbols-outlined is-error">error_outline</span>
          </div>
          <div>
            <p>{labels.failedDelivery}</p>
            <strong>{resolvedMetrics.failedDeliveries}</strong>
          </div>
        </article>
      </section>

      <section className="campaigns-table-card">
        <div className="campaigns-table-toolbar">
          <div className="campaigns-filter-tabs">
            {STATUS_FILTERS.map((filter) => (
              <button
                key={filter}
                type="button"
                className={filter === statusFilter ? 'campaigns-filter-pill is-active' : 'campaigns-filter-pill'}
                onClick={() => setStatusFilter(filter)}
              >
                {getFilterLabel(filter, labels)}
              </button>
            ))}
          </div>

          <div className="campaigns-table-controls">
            <label className="campaigns-search-field">
              <span className="material-symbols-outlined">search</span>
              <input
                type="search"
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder={labels.searchPlaceholder}
              />
            </label>

            <label className="campaigns-sort-field">
              <span className="material-symbols-outlined">filter_list</span>
              <select value={sortBy} onChange={(event) => setSortBy(event.target.value as SortOption)}>
                <option value="newest">{labels.sortNewest}</option>
                <option value="oldest">{labels.sortOldest}</option>
                <option value="delivery">{labels.sortDelivery}</option>
              </select>
            </label>
          </div>
        </div>

        <div className="campaigns-table-wrap">
          <table className="campaigns-table">
            <thead>
              <tr>
                <th>{labels.campaignName}</th>
                <th>{labels.audience}</th>
                <th>{labels.date}</th>
                <th>{labels.status}</th>
                <th>{labels.deliveryRate}</th>
                <th className="is-right">{labels.actions}</th>
              </tr>
            </thead>
            <tbody>
              {filteredCampaigns.map((campaign) => (
                <tr key={campaign.id}>
                  <td>
                    <Link href={`/dashboard/campaigns/${campaign.id}`} className="campaigns-name-link">
                      <span>{campaign.name}</span>
                      <small>ID: {campaign.code}</small>
                    </Link>
                  </td>
                  <td>
                    <div className="campaigns-audience-cell">
                      <span className="material-symbols-outlined">group</span>
                      <div>
                        <span>{campaign.audience}</span>
                        <small>{campaign.audienceGroup}</small>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div className={campaign.status === 'Scheduled' ? 'campaigns-date-cell is-scheduled' : 'campaigns-date-cell'}>
                      <span>{campaign.dateLabel}</span>
                      {campaign.timeLabel ? <small>{campaign.timeLabel}</small> : null}
                    </div>
                  </td>
                  <td>
                    <span className={getStatusClassName(campaign.status)}>
                      {campaign.status === 'Failed' ? (
                        <span className="material-symbols-outlined">error</span>
                      ) : (
                        <span className="campaigns-status-dot" />
                      )}
                      {getStatusLabel(campaign.status, labels)}
                    </span>
                  </td>
                  <td>
                    {campaign.deliveryRate === null ? (
                      <span className="campaigns-pending-text">{labels.pendingSend}</span>
                    ) : (
                      <div className="campaigns-delivery-cell">
                        <div className="campaigns-progress-track">
                          <span
                            className={campaign.status === 'Failed' ? 'campaigns-progress-bar is-failed' : 'campaigns-progress-bar'}
                            style={{ width: `${Math.max(0, Math.min(campaign.deliveryRate, 100))}%` }}
                          />
                        </div>
                        <strong className={campaign.status === 'Failed' ? 'is-error' : undefined}>
                          {formatPercent(campaign.deliveryRate)}
                        </strong>
                      </div>
                    )}
                  </td>
                  <td className="is-right">
                    {campaign.status === 'Failed' ? (
                      <button type="button" className="campaigns-action-button is-error" aria-label={`${labels.retry} ${campaign.name}`}>
                        <span className="material-symbols-outlined">refresh</span>
                      </button>
                    ) : (
                      <button type="button" className="campaigns-action-button" aria-label={`${labels.actionsFor} ${campaign.name}`}>
                        <span className="material-symbols-outlined">more_vert</span>
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="campaigns-pagination">
          <p>
            {labels.showing} <strong>{filteredCampaigns.length === 0 ? 0 : 1}-{filteredCampaigns.length}</strong> {labels.of} <strong>{campaigns.length}</strong> {labels.campaigns}
          </p>
          <div className="campaigns-pagination-buttons">
            <button type="button" disabled aria-label={labels.previousPage}>
              <span className="material-symbols-outlined">chevron_left</span>
            </button>
            <button type="button" className="is-active">1</button>
            <button type="button">2</button>
            <button type="button">3</button>
            <span>...</span>
            <button type="button">25</button>
            <button type="button" aria-label={labels.nextPage}>
              <span className="material-symbols-outlined">chevron_right</span>
            </button>
          </div>
        </div>
      </section>

      <section className="campaigns-insight-grid">
        <article className="campaigns-insight-card">
          <div className="campaigns-insight-glow" />
          <div className="campaigns-insight-body">
            <h2>{labels.optimizationTitle}</h2>
            <p>
              {labels.optimizationCopyA} <strong>09:00 AM - 11:00 AM</strong> {labels.optimizationCopyB}{' '}
              <strong className="is-success">{labels.higherRate}</strong> {labels.optimizationCopyC}
            </p>
            <button type="button">{labels.viewDetails}</button>
          </div>
        </article>

        <article className="campaigns-health-card">
          <div className="campaigns-health-head">
            <h2>{labels.templateHealth}</h2>
            <span className="material-symbols-outlined">verified</span>
          </div>
          <strong>94%</strong>
          <p>{labels.healthCopy}</p>
        </article>
      </section>
    </div>
  );
}
