'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 = {
  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';
  }
}

export function CampaignsManagementBoard({ 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">Campaign Management</h1>
          <p className="campaigns-copy">Design, schedule, and track your WhatsApp broadcast performance.</p>
        </div>
        <button type="button" className="campaigns-primary-button" onClick={() => setIsCreateOpen(true)}>
          <span className="material-symbols-outlined">campaign</span>
          New Campaign
        </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>Create Campaign</p>
                <h2>Launch a new WhatsApp broadcast</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',
                    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 : 'Failed to create campaign');
                  }

                  setIsCreateOpen(false);
                  router.push(`/dashboard/campaigns/${payload.id}`);
                  router.refresh();
                } catch (error) {
                  setCreateError(error instanceof Error ? error.message : 'Failed to create campaign');
                } finally {
                  setIsCreating(false);
                }
              }}
            >
              <label>
                <span>Campaign Name</span>
                <input
                  value={createForm.name}
                  onChange={(event) => setCreateForm((current) => ({ ...current, name: event.target.value }))}
                  placeholder="Summer Launch Blast"
                  required
                />
              </label>
              <label>
                <span>Audience Label</span>
                <input
                  value={createForm.audienceLabel}
                  onChange={(event) => setCreateForm((current) => ({ ...current, audienceLabel: event.target.value }))}
                  placeholder="VIP Customer List"
                  required
                />
              </label>
              <label>
                <span>Audience Group</span>
                <input
                  value={createForm.audienceGroup}
                  onChange={(event) => setCreateForm((current) => ({ ...current, audienceGroup: event.target.value }))}
                  placeholder="High-value segment"
                  required
                />
              </label>
              <label>
                <span>Total Recipients</span>
                <input
                  type="number"
                  min="0"
                  value={createForm.totalRecipients}
                  onChange={(event) => setCreateForm((current) => ({ ...current, totalRecipients: event.target.value }))}
                  required
                />
              </label>
              <label>
                <span>Status</span>
                <select
                  value={createForm.status}
                  onChange={(event) => setCreateForm((current) => ({ ...current, status: event.target.value }))}
                >
                  <option value="Draft">Draft</option>
                  <option value="Scheduled">Scheduled</option>
                </select>
              </label>
              <label>
                <span>Scheduled At</span>
                <input
                  type="datetime-local"
                  value={createForm.scheduledAt}
                  onChange={(event) => setCreateForm((current) => ({ ...current, scheduledAt: event.target.value }))}
                />
              </label>
              <label>
                <span>Template Name</span>
                <input
                  value={createForm.templateName}
                  onChange={(event) => setCreateForm((current) => ({ ...current, templateName: event.target.value }))}
                  placeholder="summer_promo_v3"
                />
              </label>
              <label>
                <span>Language</span>
                <input
                  value={createForm.language}
                  onChange={(event) => setCreateForm((current) => ({ ...current, language: event.target.value }))}
                />
              </label>
              <label className="is-wide">
                <span>Message Title</span>
                <input
                  value={createForm.messageTitle}
                  onChange={(event) => setCreateForm((current) => ({ ...current, messageTitle: event.target.value }))}
                  placeholder="Hi {{name}}, your private offer is ready"
                />
              </label>
              <label className="is-wide">
                <span>Message Body</span>
                <textarea
                  value={createForm.messageBody}
                  onChange={(event) => setCreateForm((current) => ({ ...current, messageBody: event.target.value }))}
                  placeholder="Write the campaign body that will appear in the WhatsApp template preview."
                  rows={4}
                />
              </label>
              <label>
                <span>Primary Button</span>
                <input
                  value={createForm.primaryButton}
                  onChange={(event) => setCreateForm((current) => ({ ...current, primaryButton: event.target.value }))}
                  placeholder="Shop Now"
                />
              </label>
              <label>
                <span>Secondary Button</span>
                <input
                  value={createForm.secondaryButton}
                  onChange={(event) => setCreateForm((current) => ({ ...current, secondaryButton: event.target.value }))}
                  placeholder="View Catalog"
                />
              </label>
              <label className="is-wide">
                <span>Banner Image URL</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)}>
                  Cancel
                </button>
                <button type="submit" className="campaigns-primary-button" disabled={isCreating}>
                  <span className="material-symbols-outlined">campaign</span>
                  {isCreating ? 'Creating...' : 'Create Campaign'}
                </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>Total Messages</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>Delivery Rate</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>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>Failed Delivery</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)}
              >
                {filter}
              </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="Search campaigns..."
              />
            </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">Sort by: Newest</option>
                <option value="oldest">Sort by: Oldest</option>
                <option value="delivery">Sort by: Best Delivery</option>
              </select>
            </label>
          </div>
        </div>

        <div className="campaigns-table-wrap">
          <table className="campaigns-table">
            <thead>
              <tr>
                <th>Campaign Name</th>
                <th>Audience</th>
                <th>Date</th>
                <th>Status</th>
                <th>Delivery Rate</th>
                <th className="is-right">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" />
                      )}
                      {campaign.status}
                    </span>
                  </td>
                  <td>
                    {campaign.deliveryRate === null ? (
                      <span className="campaigns-pending-text">Pending send...</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={`Retry ${campaign.name}`}>
                        <span className="material-symbols-outlined">refresh</span>
                      </button>
                    ) : (
                      <button type="button" className="campaigns-action-button" aria-label={`Actions for ${campaign.name}`}>
                        <span className="material-symbols-outlined">more_vert</span>
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="campaigns-pagination">
          <p>
            Showing <strong>{filteredCampaigns.length === 0 ? 0 : 1}-{filteredCampaigns.length}</strong> of <strong>{campaigns.length}</strong> campaigns
          </p>
          <div className="campaigns-pagination-buttons">
            <button type="button" disabled aria-label="Previous page">
              <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="Next page">
              <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>Campaign Performance Optimization</h2>
            <p>
              Based on your recent broadcasts, campaigns sent between <strong>09:00 AM - 11:00 AM</strong> on Tuesdays
              have a <strong className="is-success">15% higher</strong> read rate. Consider scheduling your next
              template for this window.
            </p>
            <button type="button">View Details</button>
          </div>
        </article>

        <article className="campaigns-health-card">
          <div className="campaigns-health-head">
            <h2>Template Health</h2>
            <span className="material-symbols-outlined">verified</span>
          </div>
          <strong>94%</strong>
          <p>High quality rating across all approved templates.</p>
        </article>
      </section>
    </div>
  );
}
