import { useEffect, useState, useCallback } from 'react';
import { Row, Col, Skeleton, Result, Button, Typography, Card, Empty, Space } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import axios from 'axios';
import { api } from '@/lib/api';
import ProfileCard from '@/components/volunteer/dashboard/ProfileCard';
import ActionCampaignCard from '@/components/volunteer/dashboard/ActionCampaignCard';
import ActionStepsList from '@/components/volunteer/dashboard/ActionStepsList';
import TakeActionCard from '@/components/volunteer/dashboard/TakeActionCard';
import TrainingList from '@/components/volunteer/dashboard/TrainingList';
import MyEventsCard from '@/components/volunteer/dashboard/MyEventsCard';
import ActivityCard from '@/components/volunteer/dashboard/ActivityCard';
import ResourcesGrid from '@/components/volunteer/dashboard/ResourcesGrid';
import type { VolunteerDashboardResponse } from '@/components/volunteer/dashboard/types';

export default function VolunteerDashboardPage() {
  const [data, setData] = useState<VolunteerDashboardResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchDashboard = useCallback(async () => {
    setError(null);
    try {
      const res = await api.get<VolunteerDashboardResponse>('/volunteer/dashboard');
      setData(res.data);
    } catch (err) {
      if (axios.isAxiosError(err) && err.response?.status === 404) {
        setData(null);
        setError('unavailable');
      } else {
        setError('failed');
      }
    } finally {
      setLoading(false);
    }
  }, []);

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

  if (loading) {
    return (
      <div>
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={12}>
            <Card><Skeleton avatar paragraph={{ rows: 3 }} active /></Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card><Skeleton paragraph={{ rows: 4 }} active /></Card>
          </Col>
        </Row>
      </div>
    );
  }

  if (error === 'failed') {
    return (
      <Result
        status="error"
        title="Failed to load dashboard"
        subTitle="Something went wrong while loading your dashboard. Please try again."
        extra={
          <Button type="primary" icon={<ReloadOutlined />} onClick={fetchDashboard}>
            Retry
          </Button>
        }
      />
    );
  }

  if (!data) {
    return (
      <Card>
        <Empty description="Your dashboard is not yet available. Please check back soon." />
      </Card>
    );
  }

  const hasRightColumn = !!data.featuredEvent || !!data.actionCampaign;

  return (
    <div>
      <Typography.Title level={3} style={{ marginBottom: 16 }}>
        Welcome back{data.profile.name ? `, ${data.profile.name.split(' ')[0]}` : ''}
      </Typography.Title>

      <Row gutter={[16, 16]}>
        {/* ── Top section: 2 columns ── */}
        <Col xs={24} lg={hasRightColumn ? 12 : 24}>
          <Space direction="vertical" size={16} style={{ width: '100%' }}>
            <ProfileCard
              profile={data.profile}
              referral={data.referral}
              points={data.points}
              myEvents={data.myEvents}
            />
            {data.actionCampaign && (
              <ActionCampaignCard campaign={data.actionCampaign} />
            )}
          </Space>
        </Col>

        {hasRightColumn && (
          <Col xs={24} lg={12}>
            <Space direction="vertical" size={16} style={{ width: '100%' }}>
              {data.featuredEvent && (
                <TakeActionCard event={data.featuredEvent} />
              )}
              {data.actionCampaign && (
                <ActionStepsList campaign={data.actionCampaign} onRefresh={fetchDashboard} />
              )}
            </Space>
          </Col>
        )}

        {/* ── Middle section: 3-up ── */}
        <Col xs={24} md={8}>
          <TrainingList trainings={data.trainings} onRefresh={fetchDashboard} />
        </Col>
        <Col xs={24} md={8}>
          <MyEventsCard events={data.myEvents} />
        </Col>
        <Col xs={24} md={8}>
          <ActivityCard points={data.points} />
        </Col>

        {/* ── Bottom: resources ── */}
        <Col xs={24}>
          <ResourcesGrid resources={data.resources} />
        </Col>
      </Row>
    </div>
  );
}
