import { useState, useEffect } from 'react';
import {
  Drawer,
  Button,
  Input,
  Space,
  Typography,
  Popconfirm,
  message,
  theme,
  Divider,
  Empty,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  SaveOutlined,
  CloseOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import type { AuthorEntry } from '@/hooks/useBlogAuthors';

type AuthorsMap = Record<string, AuthorEntry>;

interface AuthorsManagementModalProps {
  open: boolean;
  onClose: () => void;
  authors: AuthorsMap;
  onSaved: () => void;
}

interface AuthorFormState {
  id: string;
  name: string;
  description: string;
  avatar: string;
}

const emptyForm: AuthorFormState = { id: '', name: '', description: '', avatar: '' };

export function AuthorsManagementModal({
  open,
  onClose,
  authors,
  onSaved,
}: AuthorsManagementModalProps) {
  const [messageApi, contextHolder] = message.useMessage();
  const [localAuthors, setLocalAuthors] = useState<AuthorsMap>({});
  const [editingKey, setEditingKey] = useState<string | null>(null);
  const [editForm, setEditForm] = useState<AuthorFormState>(emptyForm);
  const [addingNew, setAddingNew] = useState(false);
  const [newForm, setNewForm] = useState<AuthorFormState>(emptyForm);
  const [saving, setSaving] = useState(false);
  const [dirty, setDirty] = useState(false);

  // Sync from props when modal opens
  useEffect(() => {
    if (open) {
      setLocalAuthors({ ...authors });
      setEditingKey(null);
      setAddingNew(false);
      setNewForm(emptyForm);
      setDirty(false);
    }
  }, [open, authors]);

  const startEdit = (key: string) => {
    const entry = localAuthors[key];
    if (!entry) return;
    setEditingKey(key);
    setEditForm({
      id: key,
      name: entry.name,
      description: entry.description ?? '',
      avatar: entry.avatar ?? '',
    });
  };

  const cancelEdit = () => {
    setEditingKey(null);
    setEditForm(emptyForm);
  };

  const saveEdit = () => {
    if (!editForm.name.trim()) {
      messageApi.warning('Name is required');
      return;
    }
    const updated = { ...localAuthors };
    // If key changed, remove old and add new
    if (editingKey && editingKey !== editForm.id && editForm.id.trim()) {
      delete updated[editingKey];
    }
    const key = editForm.id.trim() || editingKey!;
    updated[key] = buildEntry(editForm);
    setLocalAuthors(updated);
    setEditingKey(null);
    setEditForm(emptyForm);
    setDirty(true);
  };

  const deleteAuthor = (key: string) => {
    const updated = { ...localAuthors };
    delete updated[key];
    setLocalAuthors(updated);
    setDirty(true);
    if (editingKey === key) cancelEdit();
  };

  const saveNewAuthor = () => {
    if (!newForm.id.trim()) {
      messageApi.warning('Author ID is required');
      return;
    }
    if (!newForm.name.trim()) {
      messageApi.warning('Name is required');
      return;
    }
    if (localAuthors[newForm.id.trim()]) {
      messageApi.warning('An author with this ID already exists');
      return;
    }
    const updated = { ...localAuthors };
    updated[newForm.id.trim()] = buildEntry(newForm);
    setLocalAuthors(updated);
    setNewForm(emptyForm);
    setAddingNew(false);
    setDirty(true);
  };

  const handleSaveAll = async () => {
    setSaving(true);
    try {
      await api.put('/docs/blog/authors', { authors: localAuthors });
      messageApi.success('Authors saved');
      setDirty(false);
      onSaved();
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data
          ?.error?.message || 'Failed to save authors';
      messageApi.error(msg);
    } finally {
      setSaving(false);
    }
  };

  const authorEntries = Object.entries(localAuthors);

  return (
    <Drawer
      title={
        <span>
          <UserOutlined style={{ marginRight: 8 }} />
          Manage Authors
        </span>
      }
      open={open}
      onClose={onClose}
      width={560}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      destroyOnClose
      extra={
        <Button
          type="primary"
          icon={<SaveOutlined />}
          onClick={handleSaveAll}
          loading={saving}
          disabled={!dirty}
        >
          Save
        </Button>
      }
    >
      {contextHolder}

      <div style={{ maxHeight: 400, overflow: 'auto' }}>
        {authorEntries.length === 0 && !addingNew && (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="No authors defined yet"
            style={{ margin: '24px 0' }}
          />
        )}

        {authorEntries.map(([key, entry]) => (
          <div key={key}>
            {editingKey === key ? (
              <AuthorEditForm
                form={editForm}
                onChange={setEditForm}
                onSave={saveEdit}
                onCancel={cancelEdit}

                showId
              />
            ) : (
              <AuthorRow
                id={key}
                entry={entry}

                onEdit={() => startEdit(key)}
                onDelete={() => deleteAuthor(key)}
              />
            )}
            <Divider style={{ margin: '8px 0' }} />
          </div>
        ))}

        {/* New author form */}
        {addingNew ? (
          <AuthorEditForm
            form={newForm}
            onChange={setNewForm}
            onSave={saveNewAuthor}
            onCancel={() => {
              setAddingNew(false);
              setNewForm(emptyForm);
            }}
            showId
            isNew
          />
        ) : (
          <Button
            type="dashed"
            icon={<PlusOutlined />}
            onClick={() => setAddingNew(true)}
            block
            style={{ marginTop: 8 }}
          >
            Add Author
          </Button>
        )}
      </div>
    </Drawer>
  );
}

function buildEntry(form: AuthorFormState): AuthorEntry {
  const entry: AuthorEntry = { name: form.name.trim() };
  if (form.description.trim()) entry.description = form.description.trim();
  if (form.avatar.trim()) entry.avatar = form.avatar.trim();
  return entry;
}

/** Read-only author row */
function AuthorRow({
  id,
  entry,
  onEdit,
  onDelete,
}: {
  id: string;
  entry: AuthorEntry;
  onEdit: () => void;
  onDelete: () => void;
}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'flex-start',
        gap: 10,
        padding: '8px 4px',
      }}
    >
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <Typography.Text strong>{entry.name}</Typography.Text>
          <Typography.Text
            type="secondary"
            style={{ fontSize: 11, fontFamily: 'monospace' }}
          >
            {id}
          </Typography.Text>
        </div>
        {entry.description && (
          <Typography.Text
            type="secondary"
            style={{ fontSize: 12, display: 'block', marginTop: 2 }}
          >
            {entry.description}
          </Typography.Text>
        )}
        {entry.avatar && (
          <Typography.Text
            type="secondary"
            style={{
              fontSize: 11,
              display: 'block',
              marginTop: 2,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            Avatar: {entry.avatar}
          </Typography.Text>
        )}
      </div>
      <Space size={4}>
        <Button type="text" size="small" icon={<EditOutlined />} onClick={onEdit} />
        <Popconfirm
          title="Delete this author?"
          onConfirm={onDelete}
          okText="Delete"
          okButtonProps={{ danger: true }}
        >
          <Button type="text" size="small" danger icon={<DeleteOutlined />} />
        </Popconfirm>
      </Space>
    </div>
  );
}

/** Inline edit / create form for an author */
function AuthorEditForm({
  form,
  onChange,
  onSave,
  onCancel,
  showId,
  isNew,
}: {
  form: AuthorFormState;
  onChange: (f: AuthorFormState) => void;
  onSave: () => void;
  onCancel: () => void;
  showId?: boolean;
  isNew?: boolean;
}) {
  const { token } = theme.useToken();

  return (
    <div
      style={{
        padding: '10px',
        borderRadius: token.borderRadius,
        background: token.colorFillQuaternary,
        display: 'flex',
        flexDirection: 'column',
        gap: 8,
      }}
    >
      {showId && (
        <Input
          size="small"
          placeholder="Author ID (e.g. jdoe)"
          value={form.id}
          onChange={(e) => onChange({ ...form, id: e.target.value })}
          addonBefore="ID"
          disabled={!isNew && !!form.id}
        />
      )}
      <Input
        size="small"
        placeholder="Display name"
        value={form.name}
        onChange={(e) => onChange({ ...form, name: e.target.value })}
        addonBefore="Name"
        autoFocus
      />
      <Input
        size="small"
        placeholder="Short description (optional)"
        value={form.description}
        onChange={(e) => onChange({ ...form, description: e.target.value })}
        addonBefore="Desc"
      />
      <Input
        size="small"
        placeholder="Avatar URL (optional)"
        value={form.avatar}
        onChange={(e) => onChange({ ...form, avatar: e.target.value })}
        addonBefore="Avatar"
      />
      <Space size={8}>
        <Button size="small" type="primary" icon={<SaveOutlined />} onClick={onSave}>
          {isNew ? 'Add' : 'Update'}
        </Button>
        <Button size="small" icon={<CloseOutlined />} onClick={onCancel}>
          Cancel
        </Button>
      </Space>
    </div>
  );
}
