'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Alert, App, Button, Result, Skeleton, Tabs, Tooltip } from 'antd';
import { Icon } from '../ui/Icon';
import { UserAvatar } from '../ui/UserAvatar';
import { fmtDate, relTime } from '../platform/platformFormat';
import { ApiError } from '../../lib/api';
import { canDeleteRecords, leadsApi, notifyLeadsChanged, type DirectoryUser, type Lead } from '../../lib/leads';
import type { AuthUser } from '../../context/AuthContext';
import { LeadActivity } from './LeadActivity';
import { LeadStatusBadge, leadSubtitle } from './LeadBits';
import { LeadConvertModal, LeadConvertedCard } from './LeadConvertModal';
import { LeadDetailsGrid } from './LeadDetails';
import { LeadFormModal } from './LeadFormModal';
import { useDeleteLead } from './useDeleteLead';

export function LeadDetailView({ user, leadId }: { user: AuthUser; leadId: string }) {
  const router = useRouter();
  const { message } = App.useApp();
  const deleteLead = useDeleteLead();

  const [lead, setLead] = useState<Lead | null>(null);
  const [people, setPeople] = useState<DirectoryUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<{ status: number; text: string } | null>(null);
  const [reload, setReload] = useState(0);
  const [formOpen, setFormOpen] = useState(false);
  const [convertOpen, setConvertOpen] = useState(false);
  const [downloadingPdf, setDownloadingPdf] = useState(false);

  const handleDownloadPdf = async (id: string) => {
    setDownloadingPdf(true);
    try {
      await leadsApi.downloadPdf(id);
      message.success('Lead PDF downloaded successfully');
    } catch (err) {
      message.error((err as Error).message || 'Failed to download lead PDF');
    } finally {
      setDownloadingPdf(false);
    }
  };

  const mayDelete = canDeleteRecords(user);

  const loadLead = useCallback(() => {
    setReload((n) => n + 1);
  }, []);

  useEffect(() => {
    let active = true;
    const fetchRecord = async () => {
      await Promise.resolve();
      if (!active) return;
      setLoading(true);
      try {
        const record = await leadsApi.get(leadId);
        if (!active) return;
        setLead(record);
        setError(null);
      } catch (err) {
        if (!active) return;
        setLead(null);
        setError(err instanceof ApiError ? { status: err.status, text: err.message } : { status: 0, text: 'This lead could not be loaded.' });
      } finally {
        if (active) setLoading(false);
      }
    };
    void fetchRecord();
    return () => {
      active = false;
    };
  }, [leadId, reload]);

  useEffect(() => {
    leadsApi
      .directory()
      .then(setPeople)
      .catch(() => setPeople([]));
  }, []);

  const backLink = (
    <div className="mb-3">
      <Link href="/app/leads" className="inline-flex items-center gap-1 text-[13px] font-medium text-[var(--tcx-muted)] no-underline hover:text-[var(--tcx-primary)]">
        <Icon name="chevronLeft" size={14} />
        <span>Leads</span>
      </Link>
    </div>
  );

  if (loading && !lead) {
    return (
      <div>
        {backLink}
        <div className="tcx-surface-card p-6">
          <Skeleton avatar active paragraph={{ rows: 7 }} />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div>
        {backLink}
        <div className="tcx-surface-card p-6">
          {error.status === 404 ? (
            <Result
              status="404"
              title="Lead not found"
              subTitle="It may have been deleted, or it belongs to another organization."
              extra={
                <Link href="/app/leads">
                  <Button type="primary">Back to Leads</Button>
                </Link>
              }
            />
          ) : (
            <Alert
              type="error"
              showIcon
              title={error.text}
              action={
                <Button size="small" onClick={loadLead}>
                  Retry
                </Button>
              }
            />
          )}
        </div>
      </div>
    );
  }

  if (!lead) return null;

  return (
    <div>
      {backLink}

      <div className="mb-4 flex flex-wrap items-start gap-4">
        <UserAvatar name={lead.name} size={56} />
        <div className="min-w-[240px] flex-1">
          <h1 className="m-0 text-[26px] leading-tight font-bold tracking-[-0.025em] text-[var(--tcx-text)]">{lead.name}</h1>
          {leadSubtitle(lead) ? <p className="m-0 mt-1 text-[14px] text-[var(--tcx-muted)]">{leadSubtitle(lead)}</p> : null}
          <div className="mt-2.5 flex flex-wrap items-center gap-2.5">
            <LeadStatusBadge status={lead.status} />
          </div>
        </div>
      </div>

      {/* Action bar */}
      <div className="mb-4 flex flex-wrap items-center gap-2">
        {lead.status === 'CONVERTED' ? null : lead.status === 'UNQUALIFIED' ? (
          <Tooltip title="Dropped leads cannot be converted to customer">
            <span className="inline-block cursor-not-allowed">
              <Button type="primary" disabled icon={<Icon name="arrowRight" size={15} />}>
                Convert lead to Customer
              </Button>
            </span>
          </Tooltip>
        ) : (
          <Button type="primary" icon={<Icon name="arrowRight" size={15} />} onClick={() => setConvertOpen(true)}>
            Convert lead to Customer
          </Button>
        )}
        <Button icon={<Icon name="download" size={15} />} loading={downloadingPdf} onClick={() => void handleDownloadPdf(lead.id)}>
          Download PDF
        </Button>
        <Button icon={<Icon name="edit" size={15} />} onClick={() => setFormOpen(true)}>
          Edit
        </Button>
        {mayDelete ? (
          <Button
            type="text"
            danger
            icon={<Icon name="trash" size={15} />}
            onClick={async () => {
              if (await deleteLead(lead)) {
                router.replace('/app/leads');
              }
            }}
          >
            Delete
          </Button>
        ) : null}
      </div>

      <LeadConvertedCard lead={lead} />

      {/* TABS CONTAINER */}
      <div className="tcx-surface-card p-6">
        <Tabs
          defaultActiveKey="details"
          items={[
            {
              key: 'details',
              label: 'Lead details',
              children: (
                <div className="pt-2">
                  <div className="mb-4">
                    <h3 className="m-0 text-[15px] font-bold text-[var(--tcx-text)]">Lead Information</h3>
                    <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">Contact details, qualification status, and pipeline ownership.</p>
                  </div>
                  <div className="rounded-lg border border-[var(--tcx-border)] bg-[var(--tcx-sunken)] p-5">
                    <LeadDetailsGrid lead={lead} />
                  </div>
                  <div className="mt-4 flex flex-wrap items-center gap-4 text-[12px] text-[var(--tcx-muted)]">
                    <div>Added {fmtDate(lead.createdAt)}</div>
                    <div>•</div>
                    <div>Updated {relTime(lead.updatedAt)}</div>
                  </div>
                </div>
              ),
            },
            {
              key: 'activity',
              label: 'Activity & notes',
              children: (
                <div className="pt-2">
                  <div className="mb-4">
                    <h3 className="m-0 text-[15px] font-bold text-[var(--tcx-text)]">Activity & Team Notes</h3>
                    <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">Call logs, meeting notes, and collaborative team remarks.</p>
                  </div>
                  <LeadActivity key={lead.updatedAt} lead={lead} />
                </div>
              ),
            },
          ]}
        />
      </div>

      <LeadFormModal
        open={formOpen}
        lead={lead}
        currentUserId={user.id}
        people={people}
        onClose={() => setFormOpen(false)}
        onSaved={(saved) => {
          setFormOpen(false);
          setLead(saved);
          notifyLeadsChanged();
          message.success('Changes saved');
        }}
      />

      <LeadConvertModal
        open={convertOpen}
        lead={lead}
        onClose={() => setConvertOpen(false)}
        onConverted={(result) => {
          setLead(result.lead);
        }}
      />
    </div>
  );
}
