'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { Alert, Button, Drawer, Result, Skeleton } from 'antd';
import { Icon } from '../ui/Icon';
import { UserAvatar } from '../ui/UserAvatar';
import { ApiError } from '../../lib/api';
import { customersApi, type CustomerDetail } from '../../lib/customers';
import { inr } from '../../lib/leads';
import { RecordActivityTimeline } from '../crm/RecordActivityTimeline';
import { safeWebsiteHref } from './CustomerBits';
import { CustomerDetailsGrid, CustomerLinkedContacts, CustomerLinkedDeals } from './CustomerDetails';

export function customerSubtitle(a: { customerNumber?: string | null; industry: string | null; city: string | null }) {
  return [a.customerNumber, a.industry, a.city].filter(Boolean).join(' · ');
}

export const accountSubtitle = customerSubtitle;

/** Prototype customer side panel. */
export function CustomerDrawer({ customerId, version, canDelete, onClose, onEdit, onDelete }: { customerId: string | null; version: number; canDelete: boolean; onClose: () => void; onEdit: (customer: CustomerDetail) => void; onDelete: (customer: CustomerDetail) => void }) {
  const [customer, setCustomer] = useState<CustomerDetail | null>(null);
  const [error, setError] = useState<{ status: number; text: string } | null>(null);

  useEffect(() => {
    if (!customerId) return;
    let active = true;
    customersApi
      .get(customerId)
      .then((a) => {
        if (!active) return;
        setCustomer(a);
        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.' });
      });
    return () => {
      active = false;
    };
  }, [customerId, version]);

  const shown = customer && customer.id === customerId ? customer : null;
  const websiteHref = safeWebsiteHref(shown?.website);

  return (
    <Drawer open={Boolean(customerId)} onClose={onClose} size={560} closable={false} destroyOnHidden title={null} styles={{ body: { padding: 0 } }}>
      {error ? (
        <div className="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={<Button onClick={onClose}>Close</Button>} /> : <Alert type="error" showIcon title={error.text} />}</div>
      ) : !shown ? (
        <div className="p-6">
          <Skeleton avatar active paragraph={{ rows: 6 }} />
        </div>
      ) : (
        <>
          <div className="border-b border-[var(--tcx-border)] px-6 pt-5 pb-4">
            <div className="flex items-start gap-3.5">
              <UserAvatar name={shown.name} size={52} className="tcx-avatar-sq" />
              <div className="min-w-0 flex-1">
                <h2 className="m-0 truncate text-[20px] leading-tight font-bold text-[var(--tcx-text)]">{shown.name}</h2>
                <p className="m-0 mt-0.5 text-[13.5px] text-[var(--tcx-muted)]">{customerSubtitle(shown) || 'Customer'}</p>
              </div>
              <Link href={`/app/customers/${shown.id}`}>
                <Button size="small">Open full record</Button>
              </Link>
              <Button type="text" aria-label="Close" icon={<Icon name="x" size={18} />} onClick={onClose} />
            </div>

            <div className="mt-4 grid grid-cols-4 gap-2 rounded-[10px] border border-[var(--tcx-border)] bg-[var(--tcx-sunken)] px-3 py-2.5 text-center">
              <div>
                <div className="text-[11px] text-[var(--tcx-muted)]">Contacts</div>
                <div className="text-[14px] font-bold text-[var(--tcx-text)]">{shown.contacts.length}</div>
              </div>
              <div>
                <div className="text-[11px] text-[var(--tcx-muted)]">Deals</div>
                <div className="text-[14px] font-bold text-[var(--tcx-text)]">{shown.deals.length}</div>
              </div>
              <div>
                <div className="text-[11px] text-[var(--tcx-muted)]">Active deals</div>
                <div className="text-[14px] font-bold text-[var(--tcx-text)]">{inr(shown.openPipeline)}</div>
              </div>
              <div>
                <div className="text-[11px] text-[var(--tcx-muted)]">Won value</div>
                <div className="text-[14px] font-bold text-[var(--tcx-text)]">{inr(shown.wonToDate)}</div>
              </div>
            </div>

            <div className="mt-4 flex flex-wrap 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={() => onEdit(shown)}>
                Edit
              </Button>
              {canDelete ? (
                <Button type="text" danger icon={<Icon name="trash" size={15} />} onClick={() => onDelete(shown)}>
                  Delete
                </Button>
              ) : null}
            </div>
          </div>

          <div className="px-6 py-5">
            <h3 className="m-0 mb-3 text-[14px] font-bold text-[var(--tcx-text)]">Details</h3>
            <CustomerDetailsGrid customer={shown} />
          </div>

          <div className="border-t border-[var(--tcx-border)] px-6 py-5">
            <h3 className="m-0 mb-3 text-[14px] font-bold text-[var(--tcx-text)]">Contacts ({shown.contacts.length})</h3>
            <CustomerLinkedContacts contacts={shown.contacts} onNavigate={onClose} />
          </div>

          <div className="border-t border-[var(--tcx-border)] px-6 py-5">
            <h3 className="m-0 mb-3 text-[14px] font-bold text-[var(--tcx-text)]">Deals ({shown.deals.length})</h3>
            <CustomerLinkedDeals deals={shown.deals} />
          </div>

          <div className="border-t border-[var(--tcx-border)] px-6 py-5">
            <h3 className="m-0 mb-3 text-[14px] font-bold text-[var(--tcx-text)]">Activity</h3>
            <RecordActivityTimeline recordId={shown.id} createdLabel="Customer created" createdDetail={customerSubtitle(shown) || null} createdAt={shown.createdAt} loadNotes={customersApi.notes} addNote={customersApi.addNote} />
          </div>
        </>
      )}
    </Drawer>
  );
}

// Backwards-compatibility alias
export function AccountDrawer({ accountId, ...rest }: Omit<React.ComponentProps<typeof CustomerDrawer>, 'customerId'> & { accountId: string | null }) {
  return <CustomerDrawer customerId={accountId} {...rest} />;
}
