'use client';

import React, { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Alert, App, Button, Result, Skeleton, Tabs } from 'antd';
import { Icon } from '../ui/Icon';
import { UserAvatar } from '../ui/UserAvatar';
import { fmtDate, relTime } from '../platform/platformFormat';
import { ApiError } from '../../lib/api';
import { customersApi, notifyCustomersChanged, type CustomerDetail } from '../../lib/customers';
import { canDeleteRecords, inr, leadsApi, type DirectoryUser } from '../../lib/leads';
import type { AuthUser } from '../../context/AuthContext';
import { RecordActivityTimeline } from '../crm/RecordActivityTimeline';
import { safeWebsiteHref, useDeleteCustomer } from './CustomerBits';
import { CustomerDetailsGrid, CustomerLinkedContacts, CustomerLinkedDeals, CustomerLinkedProjects } from './CustomerDetails';
import { customerSubtitle } from './CustomerDrawer';
import { CustomerFormModal } from './CustomerFormModal';
import { CustomerContactModal } from './CustomerContactModal';
import { ProjectFormModal } from '../projects/ProjectFormModal';
import { CustomerLinkedFiles } from './CustomerLinkedFiles';
import { CustomerLinkedInvoices } from './CustomerLinkedInvoices';
import { invoicesApi } from '../../lib/finance';
import { filesApi } from '../../lib/files';
import { notifyContactsChanged } from '../../lib/contacts';

/** Full Customer record page matching prototype record layout. */
export function CustomerDetailView({ user, customerId }: { user: AuthUser; customerId: string }) {
  const router = useRouter();
  const { message } = App.useApp();
  const deleteCustomer = useDeleteCustomer();

  const [customer, setCustomer] = useState<CustomerDetail | null>(null);
  const [people, setPeople] = useState<DirectoryUser[]>([]);
  const [contactOpen, setContactOpen] = useState(false);
  const [projectModalOpen, setProjectModalOpen] = useState(false);
  const [fileCount, setFileCount] = useState<number>(0);
  const [invoiceCount, setInvoiceCount] = useState<number>(0);
  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 mayDelete = canDeleteRecords(user);
  const loadCustomer = useCallback(() => setReload((n) => n + 1), []);

  useEffect(() => {
    let active = true;
    const fetchRecord = async () => {
      await Promise.resolve();
      if (!active) return;
      setLoading(true);
      try {
        const [record, invRes, filesRes] = await Promise.all([customersApi.get(customerId), invoicesApi.list({ accountId: customerId, limit: 1 }).catch(() => ({ meta: { total: 0 } })), filesApi.list({ accountId: customerId, limit: 1 }).catch(() => ({ meta: { total: 0 } }))]);
        if (!active) return;
        setCustomer(record);
        setInvoiceCount(invRes.meta?.total ?? 0);
        setFileCount(filesRes.meta?.total ?? 0);
        setError(null);
      } catch (err) {
        if (!active) return;
        setCustomer(null);
        setError(err instanceof ApiError ? { status: err.status, text: err.message } : { status: 0, text: 'This customer could not be loaded.' });
      } finally {
        if (active) setLoading(false);
      }
    };
    void fetchRecord();
    return () => {
      active = false;
    };
  }, [customerId, reload]);

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

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

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

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

  if (!customer) return null;

  const websiteHref = safeWebsiteHref(customer.website);

  return (
    <div>
      {backLink}

      <div className="mb-4 flex flex-wrap items-center gap-4">
        <UserAvatar name={customer.name} size={64} className="tcx-avatar-lg-sq" />
        <div className="min-w-0 flex-1">
          <h1 className="m-0 text-[24px] leading-tight font-bold text-[var(--tcx-text)]">{customer.name}</h1>
          <p className="m-0 mt-1 text-[14px] text-[var(--tcx-muted)]">{customerSubtitle(customer) || 'Customer'}</p>
          <div className="mt-2.5 flex flex-wrap items-center gap-2.5">
            <span className="text-[12.5px] text-[var(--tcx-muted)]">
              {customer.contacts.length} {customer.contacts.length === 1 ? 'contact' : 'contacts'} · {customer.deals.length} {customer.deals.length === 1 ? 'deal' : 'deals'} · {customer.projects?.length || 0} {customer.projects?.length === 1 ? 'project' : 'projects'}
            </span>
          </div>
        </div>
      </div>

      <div className="mb-4 flex flex-wrap items-center gap-2">
        {websiteHref ? (
          <Button href={websiteHref} target="_blank" rel="noopener noreferrer" icon={<Icon name="globe" size={15} />}>
            Visit website
          </Button>
        ) : null}
        <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 deleteCustomer(customer)) {
                router.replace('/app/customers');
              }
            }}
          >
            Delete
          </Button>
        ) : null}
      </div>

      <div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
        <div className="tcx-surface-card px-4 py-3">
          <div className="text-[12px] text-[var(--tcx-muted)]">Contacts</div>
          <div className="mt-0.5 text-[18px] font-bold text-[var(--tcx-text)]">{customer.contacts.length}</div>
        </div>
        <div className="tcx-surface-card px-4 py-3">
          <div className="text-[12px] text-[var(--tcx-muted)]">Deals</div>
          <div className="mt-0.5 text-[18px] font-bold text-[var(--tcx-text)]">{customer.deals.length}</div>
        </div>
        <div className="tcx-surface-card px-4 py-3">
          <div className="text-[12px] text-[var(--tcx-muted)]">Open pipeline</div>
          <div className="mt-0.5 text-[18px] font-bold text-[var(--tcx-text)]">{inr(customer.openPipeline)}</div>
        </div>
        <div className="tcx-surface-card px-4 py-3">
          <div className="text-[12px] text-[var(--tcx-muted)]">Won to date</div>
          <div className="mt-0.5 text-[18px] font-bold text-[var(--tcx-text)]">{inr(customer.wonToDate)}</div>
        </div>
      </div>

      <div className="tcx-surface-card p-6">
        <Tabs
          defaultActiveKey="projects"
          items={[
            {
              key: 'projects',
              label: `Projects (${customer.projects?.length || 0})`,
              children: (
                <div className="pt-2">
                  <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
                    <div>
                      <h3 className="m-0 text-[15px] font-bold text-[var(--tcx-text)]">Customer Projects</h3>
                      <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">All delivery projects for this customer — Planned, In progress, Active, and Completed.</p>
                    </div>
                    <Button type="primary" icon={<Icon name="plus" size={13} />} onClick={() => setProjectModalOpen(true)}>
                      New project
                    </Button>
                  </div>
                  <CustomerLinkedProjects projects={customer.projects} />
                </div>
              ),
            },
            {
              key: 'deals',
              label: `Deals (${customer.deals.length})`,
              children: (
                <div className="pt-2">
                  <div className="mb-4 flex items-center justify-between">
                    <div>
                      <h3 className="m-0 text-[15px] font-bold text-[var(--tcx-text)]">Deals & Opportunities</h3>
                      <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">Sales pipeline deals associated with this customer account.</p>
                    </div>
                  </div>
                  <CustomerLinkedDeals deals={customer.deals} />
                </div>
              ),
            },
            {
              key: 'invoices',
              label: `Invoices (${invoiceCount})`,
              children: <CustomerLinkedInvoices customerId={customer.id} onCountChange={setInvoiceCount} />,
            },
            {
              key: 'files',
              label: `Files (${fileCount})`,
              children: <CustomerLinkedFiles customerId={customer.id} onCountChange={setFileCount} />,
            },
            {
              key: 'contacts',
              label: `Contacts (${customer.contacts.length})`,
              children: (
                <div className="pt-2">
                  <div className="mb-4 flex items-center justify-between">
                    <div>
                      <h3 className="m-0 text-[15px] font-bold text-[var(--tcx-text)]">Contact Persons</h3>
                      <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">People and decision makers at this client organization.</p>
                    </div>
                    <Button type="primary" icon={<Icon name="plus" size={13} />} onClick={() => setContactOpen(true)}>
                      Add contact
                    </Button>
                  </div>
                  <CustomerLinkedContacts contacts={customer.contacts} />
                </div>
              ),
            },
            {
              key: 'profile',
              label: 'Profile & Details',
              children: (
                <div className="pt-2 max-w-3xl">
                  <CustomerDetailsGrid customer={customer} />
                  <div className="mt-6 border-t border-[var(--tcx-border)] pt-4 text-[12.5px] text-[var(--tcx-muted)] flex flex-wrap gap-6">
                    <div>
                      Added: <strong className="text-[var(--tcx-text)]">{fmtDate(customer.createdAt)}</strong>
                    </div>
                    <div>
                      Last updated: <strong className="text-[var(--tcx-text)]">{relTime(customer.updatedAt)}</strong>
                    </div>
                  </div>
                </div>
              ),
            },
            {
              key: 'activity',
              label: 'Activity & Notes',
              children: (
                <div className="pt-2">
                  <RecordActivityTimeline recordId={customer.id} createdLabel="Customer created" createdDetail={customerSubtitle(customer) || null} createdAt={customer.createdAt} loadNotes={customersApi.notes} addNote={customersApi.addNote} />
                </div>
              ),
            },
          ]}
        />
      </div>

      <CustomerContactModal
        open={contactOpen}
        contact={null}
        currentUserId={user.id}
        people={people}
        defaultAccountId={customer.id}
        onClose={() => setContactOpen(false)}
        onSaved={() => {
          setContactOpen(false);
          notifyContactsChanged();
          loadCustomer();
          message.success('Contact added');
        }}
      />

      <CustomerFormModal
        open={formOpen}
        customer={customer}
        currentUserId={user.id}
        people={people}
        onClose={() => setFormOpen(false)}
        onSaved={() => {
          setFormOpen(false);
          notifyCustomersChanged();
          loadCustomer();
          message.success('Changes saved');
        }}
      />

      <ProjectFormModal
        open={projectModalOpen}
        project={null}
        currentUserId={user.id}
        initialCustomerId={customer.id}
        people={people}
        onClose={() => setProjectModalOpen(false)}
        onSaved={() => {
          setProjectModalOpen(false);
          loadCustomer();
          message.success('Project created');
        }}
      />
    </div>
  );
}

// Backwards-compatibility alias
export function AccountDetailView({ accountId, user }: { accountId: string; user: AuthUser }) {
  return <CustomerDetailView customerId={accountId} user={user} />;
}
