import { useState, useEffect, useCallback, useMemo } from 'react';
import { Card, Typography, Spin, Flex, Button } from 'antd';
import {
  LockOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import MiniDonutChart from '@/components/dashboard/MiniDonutChart';
import type { VaultwardenAdoptionData } from '@/types/api';

const { Text } = Typography;

export default function VaultwardenAdoptionCard() {
  const [data, setData] = useState<VaultwardenAdoptionData | null>(null);
  const [loading, setLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<VaultwardenAdoptionData>('/dashboard/vaultwarden-adoption');
      if (res.data.error) {
        setHasError(true);
      } else {
        setData(res.data);
        setHasError(false);
      }
    } catch {
      setHasError(true);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 10 * 60_000);
    return () => clearInterval(interval);
  }, [fetchData]);

  const donutData = useMemo(() => {
    if (!data) return [];
    return [
      { name: 'Enabled', value: data.enabled, color: '#52c41a' },
      { name: 'Invited', value: data.invited, color: '#faad14' },
      { name: 'Disabled', value: data.disabled, color: '#ff4d4f' },
    ];
  }, [data]);

  if (hasError && !data) return null;

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><LockOutlined style={{ marginRight: 6, fontSize: 15 }} />Vaultwarden</span>}
      size="small"
      extra={<Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchData} />}
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : data ? (
        <Flex gap={12} align="center">
          <div style={{ width: 90, flexShrink: 0 }}>
            <MiniDonutChart data={donutData} height={90} innerRadius={22} outerRadius={38} />
          </div>
          <div style={{ flex: 1 }}>
            <Text strong style={{ fontSize: 22 }}>{data.adoptionRate}%</Text>
            <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 6 }}>adoption rate</Text>
            <Flex gap={4} wrap="wrap">
              <Flex align="center" gap={4}>
                <div style={{ width: 8, height: 8, borderRadius: 2, background: '#52c41a' }} />
                <Text style={{ fontSize: 12 }}>{data.enabled} enabled</Text>
              </Flex>
              <Flex align="center" gap={4}>
                <div style={{ width: 8, height: 8, borderRadius: 2, background: '#faad14' }} />
                <Text style={{ fontSize: 12 }}>{data.invited} invited</Text>
              </Flex>
              {data.disabled > 0 && (
                <Flex align="center" gap={4}>
                  <div style={{ width: 8, height: 8, borderRadius: 2, background: '#ff4d4f' }} />
                  <Text style={{ fontSize: 12 }}>{data.disabled} disabled</Text>
                </Flex>
              )}
            </Flex>
            <Text type="secondary" style={{ fontSize: 11, marginTop: 4, display: 'block' }}>
              {data.total} total users
            </Text>
          </div>
        </Flex>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>Vaultwarden unavailable</Text>
      )}
    </Card>
  );
}
