'use client';
import React, { useEffect, useState, useCallback } from 'react';
import { Card, Col, Row, Space, Typography, Spin } from 'antd';
import { AppDispatch, RootState } from '@/store/store';
import { useDispatch, useSelector } from 'react-redux';
import { fetchDashboardWeekStatistics } from '../slice';
import ClosedEyeIcon from '@/components/ClosedEyeIcon';

const { Title } = Typography;

interface WeekStatisticsProps {
  loading?: boolean;
  onLoaded?: () => void;
}

const WeekStatistics: React.FC<WeekStatisticsProps> = ({ loading, onLoaded }) => {
  const dispatch: AppDispatch = useDispatch();
  const { dashboardWeekStatistics, dashboardFilter, weekStatisticsStatus } = useSelector(
    (state: RootState) => state.dashboard
  );

  const [visible, setVisible] = useState(false);
  const [weekLoading, setWeekLoading] = useState(false);

  const reversedData = dashboardWeekStatistics?.weeklyCounts?.slice()?.reverse();

  // When clicking any eye icon - only change visibility & show local spinner.
  const handleReveal = useCallback(() => {
    if (visible) return;
    setWeekLoading(true);
    setVisible(true);
  }, [visible]);

  // Fetch when visible becomes true OR when filters change (only if visible).
  useEffect(() => {
    let cancelled = false;
    if (!visible) return;

    const fetchData = async() => {
      setWeekLoading(true);
      try {
        await dispatch(fetchDashboardWeekStatistics({ isVisible: true }));
      } catch (err) {
        console.error('fetchDashboardWeekStatistics (filter change) failed', err);
      } finally {
        if (!cancelled) setWeekLoading(false);
      }
    };

    fetchData();

    return () => {
      cancelled = true;
    };
  }, [
    visible,
    dashboardFilter.launch_id,
    dashboardFilter.lead_user_city_id,
    dashboardFilter.lead_user_id,
    dashboardFilter.lead_user_role_name,
    dashboardFilter?.veiw_data,
    dispatch,
  ]);

  // Call onLoaded when data + not loading
  useEffect(() => {
    if (visible && dashboardWeekStatistics && !loading && typeof onLoaded === 'function') {
      onLoaded();
    }
  }, [visible, dashboardWeekStatistics, loading, onLoaded]);

  return (
    <Row gutter={[40, 40]} className="mb-5">
      <Col span={24}>
        <div className="dashboard-section-header">
          <Title level={4}>Last 4 Weeks Visit & Booking Statistics</Title>
        </div>
        {weekStatisticsStatus === 'loading' && visible ? (
          <Row gutter={[16, 16]} justify="center" align="middle" style={{ minHeight: 200 }}>
            <Spin size="default" />
          </Row>
        ) : (
          <Row gutter={[16, 16]}>
            {!visible
              ? Array.from({ length: 4 }).map((_, index) => (
                  <Col span={24} sm={12} md={12} lg={6} key={index}>
                    <Card className="dashboard-card visit-booking-statistics">
                      <div
                        style={{
                          height: '100%',
                          display: 'flex',
                          flexDirection: 'column',
                          justifyContent: 'center',
                          alignItems: 'center',
                          gap: 8,
                          minHeight: 160,
                        }}
                      >
                        {weekLoading ? (
                          <Spin />
                        ) : (
                          <ClosedEyeIcon
                            size={35}
                            color="#888"
                            onClick={handleReveal}
                            style={{ cursor: 'pointer' }}
                          />
                        )}
                        <span>Week {4 - index}</span>
                      </div>
                    </Card>
                  </Col>
                ))
              : reversedData?.map((item: any) => (
                  <Col span={24} sm={12} md={12} lg={6} key={item.week}>
                    <Card className="dashboard-card visit-booking-statistics">
                      <h4 className="title mb-3">
                        Week {item.week}: {item.weekDate}
                      </h4>
                      <Row gutter={[16, 16]}>
                        <Col span={8}>
                          <Space direction="vertical" size={0}>
                            <h3 className="count">{item.visitedCounts}</h3>
                            <span className="label">Visited</span>
                          </Space>
                        </Col>
                        <Col span={8}>
                          <Space direction="vertical" size={0}>
                            <h3 className="count">{item.bookedCounts}</h3>
                            <span className="label">Booking</span>
                          </Space>
                        </Col>
                        <Col span={8}>
                          <Space direction="vertical" size={0}>
                            <h3 className="count">{item.tokenDoneCounts}</h3>
                            <span className="label">Token</span>
                          </Space>
                        </Col>
                      </Row>
                      <div className="dashboard-card-info">
                        <p>
                          SV <br />
                          <span>{item.sitevisitCounts}</span>
                        </p>
                        <p>
                          OBM <br />
                          <span>{item.OBMDoneCounts}</span>
                        </p>
                        <p>
                          VC <br />
                          <span>{item.vcDoneCounts}</span>
                        </p>
                      </div>
                    </Card>
                  </Col>
                ))}
          </Row>
        )}
      </Col>
    </Row>
  );
};

export default WeekStatistics;
