import { useState, useMemo, useEffect, CSSProperties } from 'react';
import {
  Layout,
  Row,
  Col,
  Card,
  Statistic,
  Table,
  List,
  Timeline,
  Typography,
  Space,
  Badge,
  Avatar,
  Menu,
  message,
  Grid,
  Tag,
  Alert
} from 'antd';
import {
  DashboardOutlined,
  ProjectOutlined,
  ApartmentOutlined,
  BarChartOutlined,
  BellOutlined,
  SettingOutlined,
  UserOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useApi } from '@/hooks/useApi';
import { JobsService } from '@/services/jobs';
import { JobConfigurationService } from '@/services/jobConfiguration';
import { ROUTES } from '@/constants/routes';
import { parseError } from '@/utils/errorHandler';
import { useAppContext } from '@/store/AppStore';

const { Title } = Typography;
const { useBreakpoint } = Grid;

interface Job {
  id: string;
  title: string;
  description?: string | null;
  job_type_id: string;
  job_status_id: string;
  job_priority_id: string;
  created_by_user_id: string;
  assigned_to_user_id?: string | null;
  department_id: string;
  team_id?: string | null;
  parent_job_id?: string | null;
  due_date?: string | null;
  started_at?: string | null;
  completed_at?: string | null;
  estimated_hours?: number | null;
  created_at: string;
  updated_at: string;
}

interface JobStatus {
  id: string;
  name: string;
  description?: string | null;
  display_order: number;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

interface JobPriority {
  id: string;
  name: string;
  level: number;
  color?: string | null;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

interface JobsListResponse {
  items: Job[];
  total: number;
  limit: number;
  offset: number;
}

interface JobStatusesResponse {
  items: JobStatus[];
  total: number;
  limit: number;
  offset: number;
}

interface JobPrioritiesResponse {
  items: JobPriority[];
  total: number;
  limit: number;
  offset: number;
}

const DashboardPage = () => {
  const navigate = useNavigate();
  const screens = useBreakpoint();
  const [messageApi, contextHolder] = message.useMessage();
  const { currentUser, unreadNotificationCount } = useAppContext();

  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);

  const {
    data: jobsData,
    loading: jobsLoading,
    error: jobsError,
    execute: fetchJobs
  } = useApi<JobsListResponse>(JobsService.list);

  const {
    data: myAssignedJobsData,
    loading: myJobsLoading,
    error: myJobsError,
    execute: fetchMyAssignedJobs
  } = useApi<JobsListResponse>(JobsService.list);

  const {
    data: jobStatusesData,
    loading: statusesLoading,
    error: statusesError,
    execute: fetchJobStatuses
  } = useApi<JobStatusesResponse>(JobConfigurationService.getJobStatuses);

  const {
    data: jobPrioritiesData,
    loading: prioritiesLoading,
    error: prioritiesError,
    execute: fetchJobPriorities
  } = useApi<JobPrioritiesResponse>(JobConfigurationService.getJobPriorities);

  useEffect(() => {
    void fetchJobs({ limit: 200, offset: 0 });
    void fetchJobStatuses({ limit: 50, offset: 0, is_active: true });
    void fetchJobPriorities({ limit: 50, offset: 0, is_active: true });
  }, [fetchJobs, fetchJobStatuses, fetchJobPriorities]);

  useEffect(() => {
    if (currentUser?.id) {
      void fetchMyAssignedJobs({ limit: 10, offset: 0, assigned_to_user_id: currentUser.id });
    }
  }, [fetchMyAssignedJobs, currentUser?.id]);

  useEffect(() => {
    if (jobsError) {
      const { message: errMsg } = parseError(jobsError);
      messageApi.error(errMsg);
    }
  }, [jobsError, messageApi]);

  useEffect(() => {
    if (myJobsError) {
      const { message: errMsg } = parseError(myJobsError);
      messageApi.error(errMsg);
    }
  }, [myJobsError, messageApi]);

  useEffect(() => {
    if (statusesError) {
      const { message: errMsg } = parseError(statusesError);
      messageApi.error(errMsg);
    }
  }, [statusesError, messageApi]);

  useEffect(() => {
    if (prioritiesError) {
      const { message: errMsg } = parseError(prioritiesError);
      messageApi.error(errMsg);
    }
  }, [prioritiesError, messageApi]);

  const jobs = jobsData?.items ?? [];
  const jobStatuses = jobStatusesData?.items ?? [];
  const jobPriorities = jobPrioritiesData?.items ?? [];
  const myAssignedJobs = myAssignedJobsData?.items ?? [];

  const statusMap = useMemo(() => {
    const map: Record<string, JobStatus> = {};
    jobStatuses.forEach(s => {
      map[s.id] = s;
    });
    return map;
  }, [jobStatuses]);

  const priorityMap = useMemo(() => {
    const map: Record<string, JobPriority> = {};
    jobPriorities.forEach(p => {
      map[p.id] = p;
    });
    return map;
  }, [jobPriorities]);

  const findStatusByName = (name: string): JobStatus | undefined => {
    return jobStatuses.find(s => s.name === name);
  };

  const newJobsCount = useMemo(() => {
    const newStatus = findStatusByName('New');
    return newStatus ? jobs.filter(j => j.job_status_id === newStatus.id).length : 0;
  }, [jobs, jobStatuses]);

  const assignedJobsCount = useMemo(() => {
    const assignedStatus = findStatusByName('Assigned');
    return assignedStatus ? jobs.filter(j => j.job_status_id === assignedStatus.id).length : 0;
  }, [jobs, jobStatuses]);

  const inProgressJobsCount = useMemo(() => {
    const inProgressStatus = findStatusByName('In Progress');
    return inProgressStatus ? jobs.filter(j => j.job_status_id === inProgressStatus.id).length : 0;
  }, [jobs, jobStatuses]);

  const pendingReviewJobsCount = useMemo(() => {
    const pendingReviewStatus = findStatusByName('Pending Review');
    return pendingReviewStatus ? jobs.filter(j => j.job_status_id === pendingReviewStatus.id).length : 0;
  }, [jobs, jobStatuses]);

  const completedJobsCount = useMemo(() => {
    const completedStatus = findStatusByName('Completed');
    return completedStatus ? jobs.filter(j => j.job_status_id === completedStatus.id).length : 0;
  }, [jobs, jobStatuses]);

  const cancelledJobsCount = useMemo(() => {
    const cancelledStatus = findStatusByName('Cancelled');
    return cancelledStatus ? jobs.filter(j => j.job_status_id === cancelledStatus.id).length : 0;
  }, [jobs, jobStatuses]);

  const overdueJobsCount = useMemo(() => {
    const now = new Date();
    return jobs.filter(j => {
      if (!j.due_date || j.completed_at !== null) return false;
      const dueDate = new Date(j.due_date);
      return dueDate < now;
    }).length;
  }, [jobs]);

  const jobsDueSoon = useMemo(() => {
    const now = new Date();
    const sevenDaysLater = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
    return jobs.filter(j => {
      if (!j.due_date || j.completed_at !== null) return false;
      const dueDate = new Date(j.due_date);
      return dueDate > now && dueDate <= sevenDaysLater;
    });
  }, [jobs]);

  const loading = jobsLoading || statusesLoading || prioritiesLoading;

  const handleRowClick = (record: Job) => {
    navigate(ROUTES.JOB_DETAIL.replace(':id', record.id));
  };

  const handleNavigateToDashboard = () => {
    navigate(ROUTES.DASHBOARD);
  };

  const handleNavigateToJobs = () => {
    navigate(ROUTES.JOBS);
  };

  const handleNavigateToDepartments = () => {
    navigate(ROUTES.DEPARTMENTS);
  };

  const handleNavigateToReports = () => {
    navigate(ROUTES.REPORTS);
  };

  const handleNavigateToNotifications = () => {
    navigate(ROUTES.NOTIFICATIONS);
  };

  const handleNavigateToConfiguration = () => {
    navigate(ROUTES.CONFIGURATION);
  };

  const menuItems = useMemo(() => [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: 'Dashboard',
      onClick: handleNavigateToDashboard
    },
    {
      key: 'jobs',
      icon: <ProjectOutlined />,
      label: 'Jobs',
      onClick: handleNavigateToJobs
    },
    {
      key: 'departments',
      icon: <ApartmentOutlined />,
      label: 'Departments',
      onClick: handleNavigateToDepartments
    },
    {
      key: 'reports',
      icon: <BarChartOutlined />,
      label: 'Reports',
      onClick: handleNavigateToReports
    },
    {
      key: 'notifications',
      icon: <BellOutlined />,
      label: 'Notifications',
      onClick: handleNavigateToNotifications
    },
    {
      key: 'configuration',
      icon: <SettingOutlined />,
      label: 'Configuration',
      onClick: handleNavigateToConfiguration
    }
  ], []);

  const myJobsColumns = useMemo(() => [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: (text: string) => text ?? '—'
    },
    {
      title: 'Priority',
      dataIndex: 'job_priority_id',
      key: 'job_priority_id',
      render: (priorityId: string) => {
        const priority = priorityMap[priorityId];
        return priority ? (
          <Tag color={priority.color ?? undefined}>{priority.name}</Tag>
        ) : '—';
      }
    },
    {
      title: 'Status',
      dataIndex: 'job_status_id',
      key: 'job_status_id',
      render: (statusId: string) => {
        const status = statusMap[statusId];
        return status ? <Badge status="processing" text={status.name} /> : '—';
      }
    },
    {
      title: 'Due Date',
      dataIndex: 'due_date',
      key: 'due_date',
      render: (date: string | null) => {
        if (!date) return '—';
        return new Date(date).toLocaleDateString();
      }
    }
  ], [statusMap, priorityMap]);

  const contentPadding = (screens.xs ?? false) ? 12 : 24;

  return (
    <>
      {contextHolder}
      <div style={{ padding: contentPadding, minHeight: '100%', background: '#f5f5f5' }}>
        {jobsError && (
          <Alert
            message="Error loading jobs"
            description={parseError(jobsError).message}
            type="error"
            showIcon
            closable
            style={{ marginBottom: 16 }}
          />
        )}
        {statusesError && (
          <Alert
            message="Error loading job statuses"
            description={parseError(statusesError).message}
            type="error"
            showIcon
            closable
            style={{ marginBottom: 16 }}
          />
        )}
        {prioritiesError && (
          <Alert
            message="Error loading job priorities"
            description={parseError(prioritiesError).message}
            type="error"
            showIcon
            closable
            style={{ marginBottom: 16 }}
          />
        )}
        {myJobsError && (
          <Alert
            message="Error loading your assigned jobs"
            description={parseError(myJobsError).message}
            type="error"
            showIcon
            closable
            style={{ marginBottom: 16 }}
          />
        )}

        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={12} lg={6}>
            <Card size="small" style={{ borderLeft: '4px solid #1677ff' }} loading={loading}>
              <Statistic
                title="New"
                value={newJobsCount}
                valueStyle={{ color: '#1677ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card size="small" style={{ borderLeft: '4px solid #722ed1' }} loading={loading}>
              <Statistic
                title="Assigned"
                value={assignedJobsCount}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card size="small" style={{ borderLeft: '4px solid #fa8c16' }} loading={loading}>
              <Statistic
                title="In Progress"
                value={inProgressJobsCount}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card size="small" style={{ borderLeft: '4px solid #13c2c2' }} loading={loading}>
              <Statistic
                title="Pending Review"
                value={pendingReviewJobsCount}
                valueStyle={{ color: '#13c2c2' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card size="small" style={{ borderLeft: '4px solid #52c41a' }} loading={loading}>
              <Statistic
                title="Completed"
                value={completedJobsCount}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card size="small" style={{ borderLeft: '4px solid #8c8c8c' }} loading={loading}>
              <Statistic
                title="Cancelled"
                value={cancelledJobsCount}
                valueStyle={{ color: '#8c8c8c' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card
              size="small"
              style={{ borderLeft: '4px solid #ff4d4f', background: '#fff2f0' }}
              loading={loading}
            >
              <Statistic
                title="Overdue"
                value={overdueJobsCount}
                valueStyle={{ color: '#ff4d4f' }}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} md={12}>
            <Card title="Jobs Due Soon (Next 7 Days)" size="default" style={{ height: '100%' }} loading={loading}>
              <List
                size="small"
                dataSource={jobsDueSoon}
                style={{ maxHeight: 300, overflow: 'auto' }}
                renderItem={(job) => (
                  <List.Item
                    key={job.id}
                    style={{ cursor: 'pointer' }}
                    onClick={() => handleRowClick(job)}
                  >
                    <List.Item.Meta
                      title={job.title}
                      description={
                        <Space direction="vertical" size="small">
                          <div>
                            Priority: {priorityMap[job.job_priority_id]?.name ?? '—'}
                          </div>
                          <div>
                            Due: {job.due_date ? new Date(job.due_date).toLocaleDateString() : '—'}
                          </div>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
          <Col xs={24} md={12}>
            <Card title="Recent Activity" size="default" style={{ height: '100%' }} loading={loading}>
              <Timeline
                mode="left"
                style={{ maxHeight: 300, overflow: 'auto' }}
                items={[]}
              />
            </Card>
          </Col>
        </Row>

        <Card title="My Assigned Jobs" style={{ marginBottom: 24 }}>
          <Table
            size={(screens.xs ?? false) ? 'small' : 'middle'}
            loading={myJobsLoading}
            dataSource={myAssignedJobs}
            columns={myJobsColumns}
            rowKey="id"
            pagination={false}
            scroll={{ x: 'max-content' }}
            onRow={(record) => ({
              onClick: () => handleRowClick(record),
              style: { cursor: 'pointer' }
            })}
          />
        </Card>
      </div>
    </>
  );
};

export default DashboardPage;