import { useState, useEffect, useCallback } from 'react';
import {
  Drawer,
  Tabs,
  Table,
  Button,
  Input,
  Space,
  Tag,
  Popconfirm,
  Switch,
  message,
  Empty,
  Typography,
  ColorPicker,
  Badge,
  Tooltip,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  SyncOutlined,
  CheckOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { api } from '@/lib/api';
import type { CrmTag, UnregisteredTag } from '@/types/api';

interface TagManagementDrawerProps {
  open: boolean;
  onClose: () => void;
  onTagsChanged: () => void;
}

export default function TagManagementDrawer({ open, onClose, onTagsChanged }: TagManagementDrawerProps) {
  const [tags, setTags] = useState<CrmTag[]>([]);
  const [unregistered, setUnregistered] = useState<UnregisteredTag[]>([]);
  const [loading, setLoading] = useState(false);
  const [unregLoading, setUnregLoading] = useState(false);

  // Create form
  const [newName, setNewName] = useState('');
  const [newDescription, setNewDescription] = useState('');
  const [newColor, setNewColor] = useState('#1890ff');
  const [newSyncToListmonk, setNewSyncToListmonk] = useState(false);
  const [creating, setCreating] = useState(false);

  // Inline edit
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const [editColor, setEditColor] = useState('');
  const [editSaving, setEditSaving] = useState(false);

  const fetchTags = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await api.get<{ tags: CrmTag[] }>('/people/tags');
      setTags(data.tags);
    } catch {
      message.error('Failed to load tags');
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchUnregistered = useCallback(async () => {
    setUnregLoading(true);
    try {
      const { data } = await api.get<{ tags: UnregisteredTag[] }>('/people/tags/unregistered');
      setUnregistered(data.tags);
    } catch {
      message.error('Failed to load unregistered tags');
    } finally {
      setUnregLoading(false);
    }
  }, []);

  useEffect(() => {
    if (open) {
      fetchTags();
      fetchUnregistered();
    }
  }, [open, fetchTags, fetchUnregistered]);

  const handleCreate = async () => {
    if (!newName.trim()) return;
    setCreating(true);
    try {
      await api.post('/people/tags', {
        name: newName.trim(),
        description: newDescription || undefined,
        color: newColor || undefined,
        syncToListmonk: newSyncToListmonk,
      });
      message.success(`Tag "${newName}" created`);
      setNewName('');
      setNewDescription('');
      setNewColor('#1890ff');
      setNewSyncToListmonk(false);
      fetchTags();
      fetchUnregistered();
      onTagsChanged();
    } catch {
      message.error('Failed to create tag');
    } finally {
      setCreating(false);
    }
  };

  const startEdit = (tag: CrmTag) => {
    setEditingId(tag.id);
    setEditName(tag.name);
    setEditDescription(tag.description || '');
    setEditColor(tag.color || '#1890ff');
  };

  const handleSaveEdit = async () => {
    if (!editingId || !editName.trim()) return;
    setEditSaving(true);
    try {
      await api.put(`/people/tags/${editingId}`, {
        name: editName.trim(),
        description: editDescription || null,
        color: editColor || null,
      });
      message.success('Tag updated');
      setEditingId(null);
      fetchTags();
      onTagsChanged();
    } catch {
      message.error('Failed to update tag');
    } finally {
      setEditSaving(false);
    }
  };

  const handleDelete = async (id: string, name: string, removeFromContacts: boolean) => {
    try {
      await api.delete(`/people/tags/${id}`, {
        params: { removeFromContacts, deleteListmonkList: true },
      });
      message.success(`Tag "${name}" deleted`);
      fetchTags();
      fetchUnregistered();
      onTagsChanged();
    } catch {
      message.error('Failed to delete tag');
    }
  };

  const handleSync = async (id: string) => {
    try {
      const { data } = await api.post<{ total: number; synced: number; failed: number }>(
        `/people/tags/${id}/sync`,
      );
      message.success(`Synced ${data.synced}/${data.total} contacts to Listmonk`);
    } catch {
      message.error('Failed to sync tag');
    }
  };

  const handleRegister = async (name: string) => {
    try {
      await api.post('/people/tags', { name });
      message.success(`Tag "${name}" registered`);
      fetchTags();
      fetchUnregistered();
      onTagsChanged();
    } catch {
      message.error('Failed to register tag');
    }
  };

  const handleRegisterAll = async () => {
    try {
      const { data } = await api.post<{ registered: number }>('/people/tags/register-all', {});
      message.success(`Registered ${data.registered} tags`);
      fetchTags();
      fetchUnregistered();
      onTagsChanged();
    } catch {
      message.error('Failed to register tags');
    }
  };

  const tagColumns: ColumnsType<CrmTag> = [
    {
      title: 'Tag',
      key: 'name',
      render: (_: unknown, record: CrmTag) => {
        if (editingId === record.id) {
          return (
            <Space>
              <ColorPicker
                size="small"
                value={editColor}
                onChange={(_, hex) => setEditColor(hex)}
              />
              <Input
                size="small"
                value={editName}
                onChange={(e) => setEditName(e.target.value)}
                style={{ width: 120 }}
                onPressEnter={handleSaveEdit}
              />
            </Space>
          );
        }
        return (
          <Space size={6}>
            {record.color && (
              <Badge color={record.color} />
            )}
            <span>{record.name}</span>
          </Space>
        );
      },
    },
    {
      title: 'Description',
      key: 'description',
      ellipsis: true,
      render: (_: unknown, record: CrmTag) => {
        if (editingId === record.id) {
          return (
            <Input
              size="small"
              value={editDescription}
              onChange={(e) => setEditDescription(e.target.value)}
              placeholder="Description..."
            />
          );
        }
        return record.description || <Typography.Text type="secondary">--</Typography.Text>;
      },
    },
    {
      title: 'Contacts',
      dataIndex: 'contactCount',
      key: 'contactCount',
      width: 80,
      align: 'center',
    },
    {
      title: 'Listmonk',
      key: 'listmonk',
      width: 80,
      align: 'center',
      render: (_: unknown, record: CrmTag) =>
        record.listmonkListId ? (
          <Tooltip title={`List ID: ${record.listmonkListId}`}>
            <Tag color="green">Synced</Tag>
          </Tooltip>
        ) : (
          <Tag>--</Tag>
        ),
    },
    {
      title: '',
      key: 'actions',
      width: 120,
      render: (_: unknown, record: CrmTag) => {
        if (editingId === record.id) {
          return (
            <Space size={4}>
              <Button
                type="text"
                size="small"
                icon={<CheckOutlined />}
                loading={editSaving}
                onClick={handleSaveEdit}
              />
              <Button
                type="text"
                size="small"
                icon={<CloseOutlined />}
                onClick={() => setEditingId(null)}
              />
            </Space>
          );
        }
        return (
          <Space size={4}>
            <Button type="text" size="small" icon={<EditOutlined />} onClick={() => startEdit(record)} />
            {record.listmonkListId && (
              <Button type="text" size="small" icon={<SyncOutlined />} onClick={() => handleSync(record.id)} />
            )}
            <Popconfirm
              title="Delete this tag?"
              description="Also remove from all contacts?"
              onConfirm={() => handleDelete(record.id, record.name, true)}
              onCancel={() => handleDelete(record.id, record.name, false)}
              okText="Remove from contacts"
              cancelText="Keep on contacts"
            >
              <Button type="text" size="small" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const unregColumns: ColumnsType<UnregisteredTag> = [
    {
      title: 'Tag Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'Used By',
      dataIndex: 'count',
      key: 'count',
      width: 80,
      render: (count: number) => `${count} contacts`,
    },
    {
      title: '',
      key: 'actions',
      width: 80,
      render: (_: unknown, record: UnregisteredTag) => (
        <Button size="small" onClick={() => handleRegister(record.name)}>
          Register
        </Button>
      ),
    },
  ];

  return (
    <Drawer
      title="Manage Tags"
      open={open}
      onClose={onClose}
      width={640}
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      destroyOnClose
    >
      <Tabs
        items={[
          {
            key: 'registered',
            label: `Registered (${tags.length})`,
            children: (
              <div>
                {/* Create form */}
                <div
                  style={{
                    display: 'flex',
                    gap: 8,
                    marginBottom: 16,
                    flexWrap: 'wrap',
                    alignItems: 'center',
                  }}
                >
                  <ColorPicker
                    size="small"
                    value={newColor}
                    onChange={(_, hex) => setNewColor(hex)}
                  />
                  <Input
                    size="small"
                    placeholder="Tag name"
                    value={newName}
                    onChange={(e) => setNewName(e.target.value)}
                    style={{ width: 140 }}
                    onPressEnter={handleCreate}
                  />
                  <Input
                    size="small"
                    placeholder="Description (optional)"
                    value={newDescription}
                    onChange={(e) => setNewDescription(e.target.value)}
                    style={{ width: 180 }}
                  />
                  <Space size={4}>
                    <Switch
                      size="small"
                      checked={newSyncToListmonk}
                      onChange={setNewSyncToListmonk}
                    />
                    <Typography.Text style={{ fontSize: 12 }}>Listmonk</Typography.Text>
                  </Space>
                  <Button
                    size="small"
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleCreate}
                    loading={creating}
                    disabled={!newName.trim()}
                  >
                    Add
                  </Button>
                </div>

                <Table<CrmTag>
                  columns={tagColumns}
                  dataSource={tags}
                  rowKey="id"
                  loading={loading}
                  pagination={false}
                  size="small"
                  locale={{ emptyText: <Empty description="No registered tags" /> }}
                />
              </div>
            ),
          },
          {
            key: 'discover',
            label: `Discover (${unregistered.length})`,
            children: (
              <div>
                {unregistered.length > 0 && (
                  <div style={{ marginBottom: 12 }}>
                    <Button size="small" onClick={handleRegisterAll}>
                      Register All ({unregistered.length})
                    </Button>
                  </div>
                )}
                <Table<UnregisteredTag>
                  columns={unregColumns}
                  dataSource={unregistered}
                  rowKey="name"
                  loading={unregLoading}
                  pagination={false}
                  size="small"
                  locale={{
                    emptyText: (
                      <Empty description="All tags in use are registered" />
                    ),
                  }}
                />
              </div>
            ),
          },
        ]}
      />
    </Drawer>
  );
}
