import { useState } from 'react';
import {
  Typography,
  Switch,
  Button,
  Input,
  Popconfirm,
  Tooltip,
  Space,
  Divider,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  TeamOutlined,
  GlobalOutlined,
  LockOutlined,
  CheckOutlined,
  CloseOutlined,
  ThunderboltOutlined,
  UserOutlined,
  CloudOutlined,
} from '@ant-design/icons';
import type {
  CalendarLayer,
  CalendarLayerType,
  CalendarVisibility,
} from '@/types/api';

const { Text } = Typography;

const PRESET_COLORS = [
  '#1890ff', '#52c41a', '#fa8c16', '#722ed1', '#eb2f96',
  '#13c2c2', '#f5222d', '#faad14', '#2f54eb', '#a0d911',
];

const VISIBILITY_ICONS: Record<CalendarVisibility, React.ReactNode> = {
  PRIVATE: <LockOutlined />,
  FRIENDS: <TeamOutlined />,
  PUBLIC: <GlobalOutlined />,
};

const VISIBILITY_LABELS: Record<CalendarVisibility, string> = {
  PRIVATE: 'Private',
  FRIENDS: 'Friends only',
  PUBLIC: 'Public',
};

const GROUP_ICONS: Record<CalendarLayerType, React.ReactNode> = {
  SYSTEM: <ThunderboltOutlined />,
  USER: <UserOutlined />,
  EXTERNAL: <CloudOutlined />,
};

const GROUP_LABELS: Record<CalendarLayerType, string> = {
  SYSTEM: 'System',
  USER: 'Personal',
  EXTERNAL: 'External',
};

interface CalendarLayerPanelProps {
  layers: CalendarLayer[];
  compact?: boolean;
  onToggle: (layerId: string, enabled: boolean) => void;
  onCreate: (name: string, color: string) => void;
  onUpdate: (layerId: string, data: Partial<CalendarLayer>) => void;
  onDelete: (layerId: string) => void;
  loading?: boolean;
}

export default function CalendarLayerPanel({
  layers,
  compact,
  onToggle,
  onCreate,
  onUpdate,
  onDelete,
  loading,
}: CalendarLayerPanelProps) {
  const [showAddForm, setShowAddForm] = useState(false);
  const [newName, setNewName] = useState('');
  const [newColor, setNewColor] = useState(PRESET_COLORS[0]!);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState('');
  const [colorPickerLayerId, setColorPickerLayerId] = useState<string | null>(null);

  const grouped = (['SYSTEM', 'USER', 'EXTERNAL'] as CalendarLayerType[]).map((type) => ({
    type,
    layers: layers.filter((l) => l.layerType === type).sort((a, b) => a.sortOrder - b.sortOrder),
  })).filter((g) => g.layers.length > 0 || g.type === 'USER');

  const handleCreate = () => {
    if (!newName.trim()) return;
    onCreate(newName.trim(), newColor);
    setNewName('');
    setNewColor(PRESET_COLORS[0]!);
    setShowAddForm(false);
  };

  const handleEditSubmit = (layerId: string) => {
    if (editName.trim()) {
      onUpdate(layerId, { name: editName.trim() });
    }
    setEditingId(null);
  };

  const handleColorChange = (layerId: string, color: string) => {
    onUpdate(layerId, { color });
    setColorPickerLayerId(null);
  };

  // Compact mode: horizontal strip with just color dots + toggle
  if (compact) {
    return (
      <div
        style={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: 8,
          padding: '8px 0',
          marginBottom: 8,
          borderBottom: '1px solid rgba(255,255,255,0.08)',
        }}
      >
        {layers.map((layer) => (
          <Tooltip key={layer.id} title={layer.name}>
            <div
              onClick={() => onToggle(layer.id, !layer.isEnabled)}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 4,
                padding: '4px 8px',
                borderRadius: 12,
                cursor: 'pointer',
                userSelect: 'none',
                background: layer.isEnabled ? 'rgba(255,255,255,0.06)' : 'transparent',
                opacity: layer.isEnabled ? 1 : 0.4,
                border: `1px solid ${layer.isEnabled ? layer.color : 'rgba(255,255,255,0.1)'}`,
                transition: 'all 0.2s',
              }}
            >
              <div
                style={{
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  background: layer.color,
                  flexShrink: 0,
                }}
              />
              <Text style={{ fontSize: 11, color: 'rgba(255,255,255,0.75)' }}>
                {layer.name}
              </Text>
            </div>
          </Tooltip>
        ))}
      </div>
    );
  }

  const renderColorDot = (layer: CalendarLayer) => {
    const isOpen = colorPickerLayerId === layer.id;
    return (
      <div style={{ position: 'relative' }}>
        <div
          onClick={() => {
            if (layer.layerType === 'SYSTEM') return;
            setColorPickerLayerId(isOpen ? null : layer.id);
          }}
          style={{
            width: 14,
            height: 14,
            borderRadius: '50%',
            background: layer.color,
            cursor: layer.layerType === 'SYSTEM' ? 'default' : 'pointer',
            flexShrink: 0,
            border: '2px solid rgba(255,255,255,0.15)',
            transition: 'transform 0.15s',
          }}
        />
        {isOpen && (
          <div
            style={{
              position: 'absolute',
              top: 20,
              left: 0,
              zIndex: 10,
              background: '#1b2838',
              border: '1px solid rgba(255,255,255,0.12)',
              borderRadius: 8,
              padding: 8,
              display: 'flex',
              flexWrap: 'wrap',
              gap: 6,
              width: 160,
              boxShadow: '0 4px 12px rgba(0,0,0,0.4)',
            }}
          >
            {PRESET_COLORS.map((c) => (
              <div
                key={c}
                onClick={() => handleColorChange(layer.id, c)}
                style={{
                  width: 24,
                  height: 24,
                  borderRadius: '50%',
                  background: c,
                  cursor: 'pointer',
                  border: c === layer.color ? '2px solid #fff' : '2px solid transparent',
                  transition: 'transform 0.15s',
                }}
              />
            ))}
          </div>
        )}
      </div>
    );
  };

  const renderLayerRow = (layer: CalendarLayer) => {
    const isEditing = editingId === layer.id;
    const vis = layer.visibility;

    return (
      <div
        key={layer.id}
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          padding: '6px 0',
          opacity: layer.isEnabled ? 1 : 0.5,
          transition: 'opacity 0.2s',
        }}
      >
        {renderColorDot(layer)}

        {isEditing ? (
          <Input
            size="small"
            value={editName}
            onChange={(e) => setEditName(e.target.value)}
            onPressEnter={() => handleEditSubmit(layer.id)}
            onBlur={() => handleEditSubmit(layer.id)}
            autoFocus
            style={{ flex: 1, fontSize: 13 }}
          />
        ) : (
          <Text
            style={{
              flex: 1,
              fontSize: 13,
              color: 'rgba(255,255,255,0.85)',
              cursor: layer.layerType !== 'SYSTEM' ? 'pointer' : 'default',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
            onClick={() => {
              if (layer.layerType !== 'SYSTEM') {
                setEditingId(layer.id);
                setEditName(layer.name);
              }
            }}
          >
            {layer.name}
          </Text>
        )}

        <Tooltip title={VISIBILITY_LABELS[vis]}>
          <span
            style={{
              fontSize: 12,
              color: vis === 'PUBLIC' ? 'rgba(82,196,26,0.7)' : 'rgba(255,255,255,0.35)',
              cursor: layer.layerType !== 'SYSTEM' ? 'pointer' : 'default',
            }}
            onClick={() => {
              if (layer.layerType === 'SYSTEM') return;
              const cycle: CalendarVisibility[] = ['PRIVATE', 'FRIENDS', 'PUBLIC'];
              const next = cycle[(cycle.indexOf(vis) + 1) % cycle.length];
              onUpdate(layer.id, { visibility: next });
            }}
          >
            {VISIBILITY_ICONS[vis]}
          </span>
        </Tooltip>

        <Switch
          size="small"
          checked={layer.isEnabled}
          onChange={(checked) => onToggle(layer.id, checked)}
        />

        {layer.layerType !== 'SYSTEM' && (
          <Popconfirm
            title="Delete this layer?"
            description="All items in this layer will be deleted."
            onConfirm={() => onDelete(layer.id)}
            okText="Delete"
            okButtonProps={{ danger: true }}
          >
            <Button
              type="text"
              size="small"
              icon={<DeleteOutlined />}
              style={{ color: 'rgba(255,255,255,0.25)', padding: '0 4px' }}
            />
          </Popconfirm>
        )}
      </div>
    );
  };

  return (
    <div
      style={{
        background: 'rgba(255,255,255,0.03)',
        borderRadius: 8,
        border: '1px solid rgba(255,255,255,0.08)',
        padding: '12px 16px',
        display: 'flex',
        flexDirection: 'column',
        gap: 4,
      }}
    >
      <Text strong style={{ color: 'rgba(255,255,255,0.85)', fontSize: 14, marginBottom: 4 }}>
        Layers
      </Text>

      {loading && (
        <Text type="secondary" style={{ fontSize: 12, padding: '8px 0' }}>
          Loading layers...
        </Text>
      )}

      {grouped.map((group) => (
        <div key={group.type}>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              padding: '6px 0 2px',
            }}
          >
            <span style={{ color: 'rgba(255,255,255,0.35)', fontSize: 11 }}>
              {GROUP_ICONS[group.type]}
            </span>
            <Text
              type="secondary"
              style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.5 }}
            >
              {GROUP_LABELS[group.type]}
            </Text>
          </div>
          {group.layers.map(renderLayerRow)}
          {group.layers.length === 0 && (
            <Text type="secondary" style={{ fontSize: 12, padding: '4px 0 4px 22px', display: 'block' }}>
              No layers
            </Text>
          )}
          <Divider style={{ margin: '6px 0' }} />
        </div>
      ))}

      {showAddForm ? (
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            gap: 8,
            padding: '8px 0',
          }}
        >
          <Input
            size="small"
            placeholder="Layer name"
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            onPressEnter={handleCreate}
            autoFocus
          />

          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {PRESET_COLORS.map((c) => (
              <div
                key={c}
                onClick={() => setNewColor(c)}
                style={{
                  width: 20,
                  height: 20,
                  borderRadius: '50%',
                  background: c,
                  cursor: 'pointer',
                  border: c === newColor ? '2px solid #fff' : '2px solid transparent',
                }}
              />
            ))}
          </div>

          <Space>
            <Button
              size="small"
              type="primary"
              icon={<CheckOutlined />}
              onClick={handleCreate}
              disabled={!newName.trim()}
            >
              Add
            </Button>
            <Button
              size="small"
              icon={<CloseOutlined />}
              onClick={() => setShowAddForm(false)}
            >
              Cancel
            </Button>
          </Space>
        </div>
      ) : (
        <Button
          type="dashed"
          size="small"
          icon={<PlusOutlined />}
          onClick={() => setShowAddForm(true)}
          block
          style={{ marginTop: 4 }}
        >
          Add Layer
        </Button>
      )}
    </div>
  );
}
