'use client';

import React, { useEffect, useState } from 'react';
import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
import api from '@/lib/api';

type BankField = {
  label: string;
  value: string;
  copyable?: boolean;
};

type ImpactPoint = {
  title: string;
  text: string;
};

type DonatePageContent = {
  badge: string;
  title: string;
  title_highlight: string;
  description: string;
  bank_eyebrow: string;
  bank_heading: string;
  bank_description: string;
  bank_fields: BankField[];
  after_give_title: string;
  after_give_text: string;
  confirmation_email: string;
  contact_eyebrow: string;
  contact_heading: string;
  contact_description: string;
  email: string;
  email_note: string;
  phone: string;
  phone_note: string;
  address: string;
  impact_heading: string;
  impact_points: ImpactPoint[];
};

const FALLBACK_PAGE: DonatePageContent = {
  badge: 'Get involved',
  title: 'Donate',
  title_highlight: 'now',
  description:
    'Your contribution helps SSEOA reach more students with Community-Based Education, early childhood classes, literacy, and livelihood skills. Every gift counts.',
  bank_eyebrow: 'Bank transfer',
  bank_heading: 'Bank details',
  bank_description:
    'Make a direct transfer to our account. Please include your name and contact information in the transfer reference.',
  bank_fields: [
    { label: 'Bank Name', value: 'Afghanistan International Bank (AIB)' },
    { label: 'Account Name', value: 'Shining Star Educational Organization of Afghanistan (SSEOA)' },
    { label: 'Account Number', value: '0263112100548701', copyable: true },
    { label: 'SWIFT Code', value: 'AFIBAAFKAXXX', copyable: true },
    { label: 'Account Type / Currency', value: 'USD' },
  ],
  after_give_title: 'After you give',
  after_give_text:
    'Please email a confirmation to {email} with your name, donation amount, and transfer reference so we can acknowledge your contribution.',
  confirmation_email: 'info@sseoa.af',
  contact_eyebrow: 'Questions',
  contact_heading: 'Contact us',
  contact_description: 'Need help making a donation? Reach us by email, phone, or at our Kabul office.',
  email: 'info@sseoa.af',
  email_note: 'General inquiries and donation confirmations',
  phone: '020 220 5107',
  phone_note: 'Nematullah Rahi, General Director',
  address: 'House #6, Street #7\nQala-e-Fatullah\nKabul, Afghanistan',
  impact_heading: 'Why your donation matters',
  impact_points: [
    {
      title: 'Direct impact.',
      text: 'Gifts fund classrooms, teachers, and learning materials for girls and remote communities.',
    },
    {
      title: 'Accountability.',
      text: 'We keep clear records and acknowledge every contribution.',
    },
    {
      title: 'Local delivery.',
      text: 'SSEOA works alongside communities so education stays in local hands.',
    },
  ],
};

function CopyButton({ value }: { value: string }) {
  const [copied, setCopied] = useState(false);

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(value);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1800);
    } catch {
      setCopied(false);
    }
  };

  return (
    <button
      type="button"
      onClick={copy}
      className="rounded-lg p-2 text-navy-800 transition-colors hover:bg-primary-50 hover:text-primary-700"
      title={copied ? 'Copied' : 'Copy to clipboard'}
      aria-label={copied ? 'Copied' : `Copy ${value}`}
    >
      {copied ? (
        <svg className="h-5 w-5 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
        </svg>
      ) : (
        <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
          />
        </svg>
      )}
    </button>
  );
}

function phoneHref(phone: string): string {
  return `tel:${phone.replace(/[^\d+]/g, '')}`;
}

function renderAfterGiveText(text: string, email: string) {
  const parts = text.split('{email}');
  if (parts.length === 1) {
    return text;
  }

  return parts.map((part, index) => (
    <React.Fragment key={index}>
      {part}
      {index < parts.length - 1 ? (
        <a href={`mailto:${email}`} className="font-semibold text-navy-800 hover:text-primary-600">
          {email}
        </a>
      ) : null}
    </React.Fragment>
  ));
}

export default function DonatePage() {
  const [page, setPage] = useState<DonatePageContent>(FALLBACK_PAGE);

  useEffect(() => {
    const fetchPage = async () => {
      try {
        const response: any = await api.getDonatePage();
        const data = response?.data ?? response;
        if (!data || typeof data !== 'object') return;

        setPage({
          badge: data.badge || FALLBACK_PAGE.badge,
          title: data.title || FALLBACK_PAGE.title,
          title_highlight: data.title_highlight || FALLBACK_PAGE.title_highlight,
          description: data.description || FALLBACK_PAGE.description,
          bank_eyebrow: data.bank_eyebrow || FALLBACK_PAGE.bank_eyebrow,
          bank_heading: data.bank_heading || FALLBACK_PAGE.bank_heading,
          bank_description: data.bank_description || FALLBACK_PAGE.bank_description,
          bank_fields:
            Array.isArray(data.bank_fields) && data.bank_fields.length > 0
              ? data.bank_fields
              : FALLBACK_PAGE.bank_fields,
          after_give_title: data.after_give_title || FALLBACK_PAGE.after_give_title,
          after_give_text: data.after_give_text || FALLBACK_PAGE.after_give_text,
          confirmation_email: data.confirmation_email || FALLBACK_PAGE.confirmation_email,
          contact_eyebrow: data.contact_eyebrow || FALLBACK_PAGE.contact_eyebrow,
          contact_heading: data.contact_heading || FALLBACK_PAGE.contact_heading,
          contact_description: data.contact_description || FALLBACK_PAGE.contact_description,
          email: data.email || FALLBACK_PAGE.email,
          email_note: data.email_note || FALLBACK_PAGE.email_note,
          phone: data.phone || FALLBACK_PAGE.phone,
          phone_note: data.phone_note || FALLBACK_PAGE.phone_note,
          address: data.address || FALLBACK_PAGE.address,
          impact_heading: data.impact_heading || FALLBACK_PAGE.impact_heading,
          impact_points:
            Array.isArray(data.impact_points) && data.impact_points.length > 0
              ? data.impact_points
              : FALLBACK_PAGE.impact_points,
        });
      } catch (error) {
        console.error('Failed to load donate page:', error);
      }
    };

    fetchPage();
  }, []);

  const addressLines = page.address.split('\n').filter(Boolean);

  return (
    <div className="min-h-screen bg-white">
      <Header />

      <section className="relative overflow-hidden border-b border-secondary-200 bg-white pt-28 pb-12 sm:pt-32 sm:pb-16">
        <div className="pointer-events-none absolute -left-24 top-10 h-64 w-64 rounded-full bg-primary-500/10 blur-3xl" />
        <div className="pointer-events-none absolute -right-16 bottom-0 h-56 w-56 rounded-full bg-navy-800/5 blur-3xl" />

        <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <span className="inline-flex items-center gap-2 rounded-full border border-primary-500/30 bg-primary-500/10 px-4 py-1.5 text-xs font-bold uppercase tracking-widest text-primary-700">
            <span className="h-1.5 w-1.5 rounded-full bg-primary-500" />
            {page.badge}
          </span>

          <h1 className="mt-5 text-4xl font-black leading-tight text-neutral-900 sm:text-5xl md:text-6xl">
            {page.title}{' '}
            <span className="relative inline-block text-primary-600">
              {page.title_highlight}
              <svg
                className="pointer-events-none absolute inset-x-0 top-full mt-1 h-2.5 w-full text-primary-400 sm:h-3"
                viewBox="0 0 80 12"
                preserveAspectRatio="none"
                aria-hidden
              >
                <path
                  d="M2 9C22 2 58 2 78 9"
                  stroke="currentColor"
                  strokeWidth="4"
                  strokeLinecap="round"
                  fill="none"
                />
              </svg>
            </span>
          </h1>

          <p className="mt-6 max-w-2xl text-lg leading-relaxed text-neutral-600">{page.description}</p>
        </div>
      </section>

      <section className="bg-secondary-50 py-12 md:py-20">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
            <div className="rounded-2xl border border-secondary-200 bg-white p-6 sm:p-8 md:p-10">
              <p className="text-xs font-bold uppercase tracking-widest text-primary-600">{page.bank_eyebrow}</p>
              <h2 className="mt-2 text-2xl font-black text-neutral-900 sm:text-3xl">{page.bank_heading}</h2>
              <p className="mt-3 text-neutral-600">{page.bank_description}</p>

              <div className="mt-8 space-y-5 rounded-2xl border border-secondary-200 bg-secondary-50 p-5 sm:p-6">
                {page.bank_fields.map((field) => (
                  <div key={field.label}>
                    <p className="text-xs font-bold uppercase tracking-widest text-neutral-400">{field.label}</p>
                    <div className="mt-1 flex items-center gap-2">
                      <p className={`text-base font-semibold text-neutral-900 ${field.copyable ? 'font-mono' : ''}`}>
                        {field.value}
                      </p>
                      {field.copyable ? <CopyButton value={field.value} /> : null}
                    </div>
                  </div>
                ))}
              </div>

              <div className="mt-6 rounded-2xl border border-primary-200 bg-primary-50 p-5">
                <h3 className="font-bold text-neutral-900">{page.after_give_title}</h3>
                <p className="mt-2 text-sm leading-relaxed text-neutral-700">
                  {renderAfterGiveText(page.after_give_text, page.confirmation_email)}
                </p>
              </div>
            </div>

            <div className="space-y-8">
              <div className="rounded-2xl border border-secondary-200 bg-white p-6 sm:p-8 md:p-10">
                <p className="text-xs font-bold uppercase tracking-widest text-primary-600">{page.contact_eyebrow}</p>
                <h2 className="mt-2 text-2xl font-black text-neutral-900 sm:text-3xl">{page.contact_heading}</h2>
                <p className="mt-3 text-neutral-600">{page.contact_description}</p>

                <ul className="mt-8 space-y-6">
                  <li>
                    <p className="text-xs font-bold uppercase tracking-widest text-neutral-400">Email</p>
                    <a
                      href={`mailto:${page.email}`}
                      className="mt-1 inline-block font-semibold text-navy-800 hover:text-primary-600"
                    >
                      {page.email}
                    </a>
                    <p className="mt-1 text-sm text-neutral-500">{page.email_note}</p>
                  </li>
                  <li>
                    <p className="text-xs font-bold uppercase tracking-widest text-neutral-400">Phone</p>
                    <a
                      href={phoneHref(page.phone)}
                      className="mt-1 inline-block font-semibold text-navy-800 hover:text-primary-600"
                    >
                      {page.phone}
                    </a>
                    <p className="mt-1 text-sm text-neutral-500">{page.phone_note}</p>
                  </li>
                  <li>
                    <p className="text-xs font-bold uppercase tracking-widest text-neutral-400">Address</p>
                    <address className="mt-1 not-italic font-semibold leading-relaxed text-neutral-800">
                      {addressLines.map((line) => (
                        <React.Fragment key={line}>
                          {line}
                          <br />
                        </React.Fragment>
                      ))}
                    </address>
                  </li>
                </ul>
              </div>

              <div className="rounded-2xl bg-navy-800 p-6 text-white sm:p-8">
                <h3 className="text-xl font-black">{page.impact_heading}</h3>
                <ul className="mt-5 space-y-4 text-sm leading-relaxed text-white/80">
                  {page.impact_points.map((point) => (
                    <li key={point.title}>
                      <span className="font-bold text-primary-400">{point.title}</span> {point.text}
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </div>
  );
}
