import {
  mdiAccountConvertOutline,
  mdiArchiveOutline,
  mdiEmailOutline,
  mdiFormTextbox,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import React from 'react';
import type { ReactElement } from 'react';
import BaseIcon from '../components/BaseIcon';
import SectionMain from '../components/SectionMain';
import { getPageTitle } from '../config';
import LayoutAuthenticated from '../layouts/Authenticated';

type IntakeLead = {
  id: string;
  name: string;
  email: string;
  company?: string;
  role_title?: string;
  package_name?: string;
  preferred_time?: string;
  goal?: string;
  challenge?: string;
  desired_outcome?: string;
  status: string;
  consent_ai_notes?: boolean;
};

function Panel({
  children,
  className = '',
}: {
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <section
      className={`rounded-none border border-[#19192d]/10 bg-white ${className}`}
    >
      {children}
    </section>
  );
}

export default function IntakeLeads() {
  const [leads, setLeads] = React.useState<IntakeLead[]>([]);
  const [updatingLeadId, setUpdatingLeadId] = React.useState('');
  const [notice, setNotice] = React.useState('');

  async function loadLeads() {
    const response = await axios.get('/coaching/intake-leads');
    setLeads(response.data);
  }

  React.useEffect(() => {
    loadLeads();
  }, []);

  async function convertLead(leadId: string) {
    setUpdatingLeadId(leadId);
    setNotice('');

    try {
      const response = await axios.post(`/coaching/intake-leads/${leadId}/convert`);
      await loadLeads();

      if (response.data.invite_sent) {
        setNotice('Client workspace created. Invitation email was sent.');
      } else {
        setNotice('Client workspace created. Email is not configured, so no invitation email was sent.');
      }
    } catch (error: any) {
      setNotice(error.response?.data || 'Could not convert intake lead.');
    } finally {
      setUpdatingLeadId('');
    }
  }

  async function archiveLead(leadId: string) {
    setUpdatingLeadId(leadId);
    setNotice('');
    const response = await axios.patch(
      `/coaching/intake-leads/${leadId}/status`,
      {
        status: 'archived',
      },
    );
    setLeads((current) =>
      current.map((lead) => {
        if (lead.id === leadId) {
          return response.data;
        }

        return lead;
      }),
    );
    setUpdatingLeadId('');
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Intake Leads')}</title>
      </Head>
      <SectionMain>
        <div className='mx-auto max-w-7xl'>
          <div className='mb-4 rounded-none bg-[#19192d] p-7 text-white'>
            <div className='flex items-center gap-3 text-[#147568]'>
              <BaseIcon path={mdiFormTextbox} size={18} />
              <span className='text-xs font-semibold uppercase tracking-[0.22em]'>
                Intake
              </span>
            </div>
            <h1 className='mt-3 text-xl font-semibold'>Intake leads</h1>
            <p className='mt-2 max-w-2xl text-sm leading-6 text-[#fffdf9]'>
              Review website submissions and convert good fits into client
              records.
            </p>
          </div>

          {notice && (
            <div className='mb-4 rounded-none border border-[#19192d]/10 bg-white p-4 text-sm font-semibold text-[#19192d]'>
              {notice}
            </div>
          )}

          <div className='grid gap-6'>
            {leads.map((lead) => (
              <Panel key={lead.id} className='p-5'>
                <div className='flex flex-col justify-between gap-6 lg:flex-row lg:items-start'>
                  <div>
                    <div className='flex flex-wrap items-center gap-3'>
                      <h2 className='text-lg font-semibold text-[#19192d]'>
                        {lead.name}
                      </h2>
                      <span className='rounded-none bg-[#fffdf9] px-3 py-1 text-xs font-semibold text-[#147568]'>
                        {lead.status}
                      </span>
                    </div>
                    <p className='mt-1 text-sm text-[#5f6675]'>
                      {lead.role_title || 'Role not provided'} ·{' '}
                      {lead.company || 'Company not provided'}
                    </p>
                    <div className='mt-3 flex flex-wrap gap-2'>
                      <span className='rounded-none border border-[#19192d]/10 bg-white px-3 py-1 text-xs font-semibold text-[#19192d]'>
                        {lead.package_name || 'Package not selected'}
                      </span>
                      <span className='rounded-none border border-[#19192d]/10 bg-white px-3 py-1 text-xs font-semibold text-[#19192d]'>
                        {lead.preferred_time || 'Preferred time not provided'}
                      </span>
                    </div>
                    <a
                      href={`mailto:${lead.email}`}
                      className='mt-3 inline-flex items-center gap-2 text-sm font-semibold text-[#147568]'
                    >
                      <BaseIcon path={mdiEmailOutline} size={18} />
                      {lead.email}
                    </a>
                  </div>

                  <div className='flex flex-wrap gap-2'>
                    {lead.status !== 'converted' && (
                      <button
                        type='button'
                        disabled={updatingLeadId === lead.id}
                        onClick={() => convertLead(lead.id)}
                        className='inline-flex items-center gap-2 rounded-none bg-[#147568] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50'
                      >
                        <BaseIcon path={mdiAccountConvertOutline} size={18} />
                        Convert to client
                      </button>
                    )}
                    {lead.status !== 'archived' && (
                      <button
                        type='button'
                        disabled={updatingLeadId === lead.id}
                        onClick={() => archiveLead(lead.id)}
                        className='inline-flex items-center gap-2 rounded-none border border-[#19192d]/10 bg-white px-4 py-2 text-sm font-semibold text-[#19192d] disabled:opacity-50'
                      >
                        <BaseIcon path={mdiArchiveOutline} size={18} />
                        Archive
                      </button>
                    )}
                  </div>
                </div>

                <div className='mt-5 grid gap-6 lg:grid-cols-3'>
                  <div className='rounded-none bg-[#fffdf9] p-6'>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-[#147568]'>
                      Goal
                    </p>
                    <p className='mt-3 text-sm leading-6 text-[#5f6675]'>
                      {lead.goal || 'No goal provided.'}
                    </p>
                  </div>
                  <div className='rounded-none bg-[#fffdf9] p-6'>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-[#147568]'>
                      Challenge
                    </p>
                    <p className='mt-3 text-sm leading-6 text-[#5f6675]'>
                      {lead.challenge || 'No challenge provided.'}
                    </p>
                  </div>
                  <div className='rounded-none bg-[#fffdf9] p-6'>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-[#147568]'>
                      Desired outcome
                    </p>
                    <p className='mt-3 text-sm leading-6 text-[#5f6675]'>
                      {lead.desired_outcome || 'No outcome provided.'}
                    </p>
                  </div>
                </div>
              </Panel>
            ))}

            {leads.length === 0 && (
              <Panel className='p-5'>
                <p className='text-sm text-[#5f6675]'>
                  No intake leads yet. Share the public intake page from{' '}
                  <Link href='/intake' className='font-semibold text-[#147568]'>
                    /intake
                  </Link>
                  .
                </p>
              </Panel>
            )}
          </div>
        </div>
      </SectionMain>
    </>
  );
}

IntakeLeads.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};
