'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Alert, App, Button, Empty, Form, Input, Modal, Popconfirm, Skeleton, Switch, Tag, Tooltip } from 'antd';
import { Icon } from '../ui/Icon';
import { PageHeader } from '../platform/PlatformPrimitives';
import { fmtDate } from '../platform/platformFormat';
import { ApiError } from '../../lib/api';
import { servicesApi, type ServiceRecord } from '../../lib/services';

const errorText = (err: unknown, fallback: string) => (err instanceof ApiError ? err.message : fallback);

/** Services catalogue: everyone can view; only Org Admins can add, edit, switch on/off or delete. */
export function ServicesView({ canManage }: { canManage: boolean }) {
  const { message } = App.useApp();
  const [services, setServices] = useState<ServiceRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [error, setError] = useState<string | null>(null);

  // Modal State
  const [modalOpen, setModalOpen] = useState(false);
  const [editingService, setEditingService] = useState<ServiceRecord | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [form] = Form.useForm<{ name: string; description?: string; isActive: boolean }>();

  const [reload, setReload] = useState(0);
  const loadServices = useCallback(() => setReload((n) => n + 1), []);

  useEffect(() => {
    let active = true;
    servicesApi
      .list()
      .then((data) => {
        if (!active) return;
        setServices(data);
        setError(null);
      })
      .catch((err: unknown) => {
        if (active) setError(errorText(err, 'Services could not be loaded.'));
      })
      .finally(() => {
        if (active) setLoading(false);
      });
    return () => {
      active = false;
    };
  }, [reload]);

  const filteredServices = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return services;
    return services.filter((s) => s.name.toLowerCase().includes(q) || (s.description && s.description.toLowerCase().includes(q)));
  }, [services, search]);

  const handleOpenCreate = () => {
    setEditingService(null);
    setModalOpen(true);
  };

  const handleOpenEdit = (record: ServiceRecord) => {
    setEditingService(record);
    setModalOpen(true);
  };

  const handleSubmit = async (values: { name: string; description?: string; isActive: boolean }) => {
    const cleanName = values.name.trim();
    if (!cleanName) return;
    setSubmitting(true);
    try {
      if (editingService) {
        await servicesApi.update(editingService.id, {
          name: cleanName,
          description: values.description?.trim() || null,
          isActive: values.isActive,
        });
        message.success(`Service "${cleanName}" updated.`);
      } else {
        await servicesApi.create({
          name: cleanName,
          description: values.description?.trim() || null,
          isActive: values.isActive,
        });
        message.success(`Service "${cleanName}" created.`);
      }
      setModalOpen(false);
      loadServices();
    } catch (err) {
      message.error(errorText(err, 'The service could not be saved.'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleToggle = async (record: ServiceRecord) => {
    try {
      await servicesApi.toggleActive(record.id);
      setServices((prev) => prev.map((s) => (s.id === record.id ? { ...s, isActive: !s.isActive } : s)));
      message.success(record.isActive ? `Deactivated "${record.name}". It will not appear in new leads.` : `Activated "${record.name}".`);
    } catch (err) {
      message.error(errorText(err, 'The service status could not be changed.'));
    }
  };

  const handleDelete = async (record: ServiceRecord) => {
    try {
      await servicesApi.remove(record.id);
      message.success(`Service "${record.name}" deleted.`);
      loadServices();
    } catch (err) {
      message.error(errorText(err, 'The service could not be deleted.'));
    }
  };

  return (
    <div className="space-y-4">
      <PageHeader eyebrow="Sales" title="Services" subtitle="Manage company IT services, capabilities, and delivery packages for leads and deals" />

      {/* Toolbar matching Leads and Customers */}
      <div className="flex flex-wrap items-center gap-2">
        <Input prefix={<Icon name="search" size={15} className="text-[var(--tcx-muted)]" />} placeholder="Search services..." allowClear value={search} onChange={(e) => setSearch(e.target.value)} className="w-full sm:!w-[280px]" />
        <div className="text-[13px] text-[var(--tcx-muted)]">
          {filteredServices.length} {filteredServices.length === 1 ? 'service' : 'services'}
        </div>
        <div className="flex-1" />
        {canManage ? (
          <Button type="primary" icon={<Icon name="plus" size={16} />} onClick={handleOpenCreate}>
            New service
          </Button>
        ) : null}
      </div>

      {/* Main Table Card */}
      <div className="tcx-surface-card overflow-hidden">
        {error ? (
          <div className="p-6">
            <Alert
              type="error"
              showIcon
              title={error}
              action={
                <Button size="small" onClick={loadServices}>
                  Retry
                </Button>
              }
            />
          </div>
        ) : loading && services.length === 0 ? (
          <div className="p-6">
            <Skeleton active paragraph={{ rows: 6 }} />
          </div>
        ) : services.length === 0 ? (
          <div className="py-14">
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={
                <span>
                  <b className="block text-[var(--tcx-text)]">No services yet</b>
                  {canManage ? 'Add the services your company sells (e.g. Web Development, Mobile Apps, Cloud, AMC). Until then, leads use a built-in list.' : 'Your admin has not added services yet. Leads use a built-in list until then.'}
                </span>
              }
            >
              {canManage ? (
                <Button type="primary" icon={<Icon name="plus" size={16} />} onClick={handleOpenCreate}>
                  New service
                </Button>
              ) : null}
            </Empty>
          </div>
        ) : filteredServices.length === 0 ? (
          <div className="py-12">
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={
                <span>
                  <b className="block text-[var(--tcx-text)]">No matching services</b>
                  Try adjusting your search query.
                </span>
              }
            >
              <Button onClick={() => setSearch('')}>Clear search</Button>
            </Empty>
          </div>
        ) : (
          <div className="tcx-table-scroll" aria-busy={loading}>
            <table className={`tcx-table ${loading ? 'opacity-60' : ''}`}>
              <thead>
                <tr>
                  <th>Service name</th>
                  <th>Description / Scope</th>
                  <th className="tcx-right">Leads</th>
                  <th>Status</th>
                  <th>Date added</th>
                  {canManage ? <th className="tcx-right">Actions</th> : null}
                </tr>
              </thead>
              <tbody>
                {filteredServices.map((s) => (
                  <tr key={s.id}>
                    <td>
                      <div className="flex items-center gap-2.5">
                        <span className="flex h-8 w-8 flex-none items-center justify-center rounded-md bg-[var(--tcx-primary-subtle)] text-[var(--tcx-primary)]">
                          <Icon name="layers" size={16} />
                        </span>
                        <div className="font-semibold text-[var(--tcx-text)]">{s.name}</div>
                      </div>
                    </td>
                    <td>
                      <div className="max-w-md truncate text-[12.5px] text-[var(--tcx-muted)]">{s.description || '—'}</div>
                    </td>
                    <td className="tcx-right tabular-nums text-[var(--tcx-text-2)]">{s.leadCount}</td>
                    <td>
                      <div className="flex items-center gap-2">
                        {canManage ? <Switch size="small" checked={s.isActive} aria-label={`${s.isActive ? 'Deactivate' : 'Activate'} ${s.name}`} onChange={() => void handleToggle(s)} /> : null}
                        <Tag color={s.isActive ? 'success' : 'default'}>{s.isActive ? 'Active' : 'Inactive'}</Tag>
                      </div>
                    </td>
                    <td>
                      <span className="text-[12.5px] text-[var(--tcx-muted)]">{fmtDate(s.createdAt)}</span>
                    </td>
                    {canManage ? (
                      <td className="tcx-right">
                        <div className="flex items-center justify-end gap-1">
                          <Button type="text" size="small" aria-label={`Edit ${s.name}`} icon={<Icon name="edit" size={14} />} onClick={() => handleOpenEdit(s)} />
                          {s.leadCount > 0 ? (
                            <Tooltip title={`Used by ${s.leadCount} ${s.leadCount === 1 ? 'lead' : 'leads'}. Switch it off instead of deleting.`}>
                              <span>
                                <Button type="text" size="small" danger disabled aria-label={`Delete ${s.name} (in use)`} icon={<Icon name="trash" size={14} />} />
                              </span>
                            </Tooltip>
                          ) : (
                            <Popconfirm title="Delete service?" description="Only services that no lead uses can be deleted. Switch it off instead to hide it from new leads." okText="Delete" cancelText="Cancel" okButtonProps={{ danger: true }} onConfirm={() => void handleDelete(s)}>
                              <Button type="text" size="small" danger aria-label={`Delete ${s.name}`} icon={<Icon name="trash" size={14} />} />
                            </Popconfirm>
                          )}
                        </div>
                      </td>
                    ) : null}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Add / Edit Service Modal */}
      <Modal
        open={modalOpen}
        title={editingService ? 'Edit service' : 'New service'}
        onCancel={() => setModalOpen(false)}
        destroyOnHidden
        width={500}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={() => setModalOpen(false)}>Cancel</Button>
            <Button type="primary" loading={submitting} onClick={() => form.submit()}>
              {editingService ? 'Save changes' : 'Create service'}
            </Button>
          </div>
        }
      >
        <Form preserve={false} form={form} layout="vertical" initialValues={editingService ? { name: editingService.name, description: editingService.description || '', isActive: editingService.isActive } : { name: '', description: '', isActive: true }} onFinish={(v) => void handleSubmit(v)} className="mt-4">
          <Form.Item
            name="name"
            label="Service name"
            rules={[
              { required: true, whitespace: true, message: 'Enter service name' },
              { max: 120, message: '120 characters or fewer' },
            ]}
          >
            <Input placeholder="Enter service name" autoFocus />
          </Form.Item>
          <Form.Item name="description" label="Description / Scope (optional)" rules={[{ max: 2000, message: '2000 characters or fewer' }]}>
            <Input.TextArea rows={3} placeholder="Summary of deliverables, technologies, or service boundaries" />
          </Form.Item>
          {editingService ? (
            <Form.Item name="isActive" label="Active status" valuePropName="checked">
              <Switch checkedChildren="Active" unCheckedChildren="Inactive" />
            </Form.Item>
          ) : null}
        </Form>
      </Modal>
    </div>
  );
}
