import { useEffect, useState, useMemo } from 'react';
import { Typography, Table, Tag, Button, Space, message, Popconfirm, Input, Select } from 'antd';
import {
  PlusOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  DeleteOutlined,
  EyeOutlined,
  ImportOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type { Instance } from '@/types/api';
import DiscoverInstancesDrawer from '@/components/DiscoverInstancesDrawer';

const statusColors: Record<string, string> = {
  RUNNING: 'green',
  STOPPED: 'default',
  PROVISIONING: 'processing',
  ERROR: 'red',
  DESTROYING: 'orange',
};

export default function InstanceListPage() {
  const navigate = useNavigate();
  const [instances, setInstances] = useState<Instance[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [discoverOpen, setDiscoverOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('ALL');

  const filteredInstances = useMemo(() => {
    let result = instances;
    if (statusFilter !== 'ALL') {
      result = result.filter((i) => i.status === statusFilter);
    }
    if (search.trim()) {
      const q = search.toLowerCase().trim();
      result = result.filter(
        (i) =>
          i.name.toLowerCase().includes(q) ||
          i.domain.toLowerCase().includes(q) ||
          i.slug.toLowerCase().includes(q)
      );
    }
    return result;
  }, [instances, search, statusFilter]);

  const fetchInstances = async () => {
    try {
      const { data } = await api.get('/instances');
      setInstances(data.data);
    } catch {
      message.error('Failed to load instances');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchInstances();
  }, []);

  const handleDelete = async (id: string) => {
    try {
      const { data } = await api.delete(`/instances/${id}`);
      message.success(data?.message || 'Instance deleted');
      fetchInstances();
    } catch {
      message.error('Failed to delete instance');
    }
  };

  const handleStart = async (id: string) => {
    setActionLoading(id);
    try {
      await api.post(`/instances/${id}/start`);
      message.success('Instance started');
      fetchInstances();
    } catch (err: unknown) {
      const resp = (err as { response?: { data?: { error?: { message?: string } } } })?.response
        ?.data?.error;
      message.error(resp?.message || 'Failed to start instance');
    } finally {
      setActionLoading(null);
    }
  };

  const handleStop = async (id: string) => {
    setActionLoading(id);
    try {
      await api.post(`/instances/${id}/stop`);
      message.success('Instance stopped');
      fetchInstances();
    } catch (err: unknown) {
      const resp = (err as { response?: { data?: { error?: { message?: string } } } })?.response
        ?.data?.error;
      message.error(resp?.message || 'Failed to stop instance');
    } finally {
      setActionLoading(null);
    }
  };

  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record: Instance) => (
        <Space size="small">
          <a onClick={() => navigate(`/app/instances/${record.id}`)}>{name}</a>
          {record.isRegistered && <Tag color="purple">External</Tag>}
          {record.isRemote && <Tag color="cyan">Remote</Tag>}
        </Space>
      ),
    },
    {
      title: 'Domain',
      dataIndex: 'domain',
      key: 'domain',
      render: (domain: string) => (
        <Typography.Text copyable={{ text: `https://app.${domain}` }}>
          {domain}
        </Typography.Text>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => <Tag color={statusColors[status]}>{status}</Tag>,
    },
    {
      title: 'Features',
      key: 'features',
      render: (_: unknown, record: Instance) => (
        <Space size="small" wrap>
          {record.enableMedia && <Tag>Media</Tag>}
          {record.enableListmonk && <Tag>Newsletter</Tag>}
          {record.enableGancio && <Tag>Events</Tag>}
          {record.enableChat && <Tag>Chat</Tag>}
        </Space>
      ),
    },
    {
      title: 'Ports',
      key: 'ports',
      render: (_: unknown, record: Instance) => {
        const ports = record.portConfig as Record<string, number>;
        return (
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            API:{ports.api} Admin:{ports.admin}
          </Typography.Text>
        );
      },
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, record: Instance) => {
        const isLoading = actionLoading === record.id;
        const canStart = record.status === 'STOPPED' || record.status === 'ERROR';
        const canStop = record.status === 'RUNNING';
        return (
          <Space>
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/app/instances/${record.id}`)}
            />
            {canStop ? (
              <Popconfirm
                title="Stop this instance?"
                onConfirm={() => handleStop(record.id)}
              >
                <Button
                  type="text"
                  icon={<PauseCircleOutlined />}
                  loading={isLoading}
                />
              </Popconfirm>
            ) : (
              <Button
                type="text"
                icon={<PlayCircleOutlined />}
                disabled={!canStart}
                loading={isLoading}
                onClick={() => handleStart(record.id)}
              />
            )}
            <Popconfirm
              title={record.isRegistered ? 'Unregister this instance?' : 'Delete this instance?'}
              description={
                record.isRegistered
                  ? 'This removes the instance from CCP monitoring. No containers or data will be affected.'
                  : 'This will stop all containers and delete all data.'
              }
              onConfirm={() => handleDelete(record.id)}
              okText={record.isRegistered ? 'Unregister' : 'Delete'}
              okType="danger"
            >
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Typography.Title level={3} style={{ margin: 0 }}>
          Instances
        </Typography.Title>
        <Space>
          <Button
            icon={<SearchOutlined />}
            onClick={() => setDiscoverOpen(true)}
          >
            Discover Instances
          </Button>
          <Button
            icon={<ImportOutlined />}
            onClick={() => navigate('/app/instances/register')}
          >
            Register Existing
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate('/app/instances/new')}
          >
            Create Instance
          </Button>
        </Space>
      </div>

      <Space style={{ marginBottom: 16 }} wrap>
        <Input.Search
          placeholder="Search name, domain, or slug..."
          allowClear
          style={{ width: 280 }}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
        <Select
          value={statusFilter}
          onChange={setStatusFilter}
          style={{ width: 160 }}
          options={[
            { label: 'All Statuses', value: 'ALL' },
            { label: 'Running', value: 'RUNNING' },
            { label: 'Stopped', value: 'STOPPED' },
            { label: 'Error', value: 'ERROR' },
            { label: 'Provisioning', value: 'PROVISIONING' },
          ]}
        />
      </Space>

      <Table
        dataSource={filteredInstances}
        columns={columns}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 20 }}
      />

      <DiscoverInstancesDrawer
        open={discoverOpen}
        onClose={() => setDiscoverOpen(false)}
        onImported={fetchInstances}
      />
    </div>
  );
}
