import { useState, useMemo, useEffect, useCallback } from 'react';
import {
  Card,
  Button,
  Space,
  Tag,
  Descriptions,
  Tabs,
  Typography,
  List,
  Progress,
  Checkbox,
  Form,
  Input,
  Select,
  Modal,
  Table,
  Upload,
  DatePicker,
  Statistic,
  Timeline,
  Spin,
  Alert,
  Popover,
  message,
  Grid,
  Row,
  Col
} from 'antd';
import {
  ArrowLeftOutlined,
  EditOutlined,
  UserAddOutlined,
  CloseCircleOutlined,
  UndoOutlined,
  PlusOutlined,
  SendOutlined,
  DeleteOutlined,
  ClockCircleOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  InboxOutlined
} from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { useApi } from '@/hooks/useApi';
import { JobsService } from '@/services/jobs';
import { TimeLogsService } from '@/services/timeLogs';
import { ChecklistsService } from '@/services/checklists';
import { UsersService } from '@/services/users';
import { JobConfigurationService } from '@/services/jobConfiguration';
import { ROUTES } from '@/constants/routes';
import { parseError } from '@/utils/errorHandler';
import { useAppContext } from '@/store/AppStore';
import dayjs, { Dayjs } from 'dayjs';

const { useBreakpoint } = Grid;

interface JobDetail {
  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;
  job_type?: { name: string };
  job_status?: { name: string };
  job_priority?: { name: string };
  created_by_user?: { first_name?: string; last_name?: string };
  assigned_to_user?: { first_name?: string; last_name?: string } | null;
  department?: { name: string };
  team?: { name: string } | null;
  parent_job?: { title: string } | null;
  comments?: Comment[];
  attachments?: Attachment[];
  job_history?: JobHistory[];
  time_logs?: TimeLog[];
  job_tags?: JobTag[];
  checklists?: Checklist[];
}

interface Comment {
  id: string;
  job_id: string;
  user_id: string;
  content: string;
  created_at: string;
  updated_at: string;
}

interface Attachment {
  id: string;
  job_id: string;
  uploaded_by_user_id: string;
  file_name: string;
  file_path: string;
  file_type?: string | null;
  file_size: number;
  created_at: string;
  updated_at: string;
}

interface TimeLog {
  id: string;
  job_id: string;
  user_id: string;
  start_time: string;
  end_time?: string | null;
  duration_minutes?: number | null;
  notes?: string | null;
  created_at: string;
  updated_at: string;
}

interface Checklist {
  id: string;
  job_id: string;
  title: string;
  description?: string | null;
  display_order: number;
  created_at: string;
  updated_at: string;
}

interface ChecklistItem {
  id: string;
  checklist_id: string;
  description: string;
  is_completed: boolean;
  assigned_to_user_id?: string | null;
  display_order: number;
  completed_at?: string | null;
  created_at: string;
  updated_at: string;
}

interface JobHistory {
  id: string;
  job_id: string;
  user_id: string;
  action_type: string;
  field_name?: string | null;
  old_value?: string | null;
  new_value?: string | null;
  created_at: string;
  updated_at: string;
}

interface JobTag {
  id: string;
  job_id: string;
  tag_id: string;
  tag?: { name: string; color?: string | null };
}

interface User {
  id: string;
  first_name: string;
  last_name: string;
  email: string;
  role: string;
  department_id?: string | null;
}

interface Tag {
  id: string;
  name: string;
  color?: string | null;
  usage_count: number;
}

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

interface SubJob {
  id: string;
  title: string;
  job_status_id: string;
  job_priority_id: string;
  assigned_to_user_id?: string | null;
  parent_job_id?: string | null;
  created_at: string;
}

const JobDetailPage = () => {
  const navigate = useNavigate();
  const { jobId } = useParams<{ jobId: string }>();
  const [messageApi, contextHolder] = message.useMessage();
  const screens = useBreakpoint();
  const { currentUser } = useAppContext();

  const [activeTab, setActiveTab] = useState<string>('description');
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  const [assignModalVisible, setAssignModalVisible] = useState<boolean>(false);
  const [cancelModalVisible, setCancelModalVisible] = useState<boolean>(false);
  const [reopenModalVisible, setReopenModalVisible] = useState<boolean>(false);
  const [timeLogModalVisible, setTimeLogModalVisible] = useState<boolean>(false);
  const [subJobModalVisible, setSubJobModalVisible] = useState<boolean>(false);
  const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false);
  const [imagePreviewUrl, setImagePreviewUrl] = useState<string>('');
  const [tagPopoverVisible, setTagPopoverVisible] = useState<boolean>(false);
  const [activeTimerLogId, setActiveTimerLogId] = useState<string | null>(null);

  const [editForm] = Form.useForm();
  const [assignForm] = Form.useForm();
  const [commentForm] = Form.useForm();
  const [timeLogForm] = Form.useForm();
  const [checklistForm] = Form.useForm();
  const [checklistItemForm] = Form.useForm();
  const [subJobForm] = Form.useForm();

  const { data: jobDetail, loading: jobLoading, error: jobError, execute: fetchJobDetails } = useApi<JobDetail>(
    JobsService.getDetails
  );
  const { data: commentsData, execute: fetchComments } = useApi<{ items: Comment[] }>(JobsService.getComments);
  const { data: attachmentsData, execute: fetchAttachments } = useApi<{ items: Attachment[] }>(JobsService.getAttachments);
  const { data: timeLogsData, execute: fetchTimeLogs } = useApi<{ items: TimeLog[] }>(TimeLogsService.list);
  const { data: checklistsData, execute: fetchChecklists } = useApi<{ items: Checklist[] }>(ChecklistsService.list);
  const { data: checklistItemsData, execute: fetchChecklistItems } = useApi<{ items: ChecklistItem[] }>(ChecklistsService.getItems);
  const { data: jobHistoryData, execute: fetchJobHistory } = useApi<{ items: JobHistory[] }>(JobsService.getHistory);
  const { data: subJobsData, execute: fetchSubJobs } = useApi<{ items: SubJob[] }>(JobsService.list);
  const { data: usersData, execute: fetchUsers } = useApi<{ items: User[] }>(UsersService.list);
  const { data: tagsData, execute: fetchTags } = useApi<{ items: Tag[] }>(JobConfigurationService.getTags);
  const { data: jobStatusesData, execute: fetchJobStatuses } = useApi<{ items: JobStatus[] }>(JobConfigurationService.getJobStatuses);

  const comments = useMemo(() => commentsData?.items ?? [], [commentsData]);
  const attachments = useMemo(() => attachmentsData?.items ?? [], [attachmentsData]);
  const timeLogs = useMemo(() => timeLogsData?.items ?? [], [timeLogsData]);
  const checklists = useMemo(() => checklistsData?.items ?? [], [checklistsData]);
  const checklistItems = useMemo(() => checklistItemsData?.items ?? [], [checklistItemsData]);
  const jobHistory = useMemo(() => jobHistoryData?.items ?? [], [jobHistoryData]);
  const subJobs = useMemo(() => subJobsData?.items ?? [], [subJobsData]);
  const users = useMemo(() => usersData?.items ?? [], [usersData]);
  const availableTags = useMemo(() => tagsData?.items ?? [], [tagsData]);
  const jobStatuses = useMemo(() => jobStatusesData?.items ?? [], [jobStatusesData]);

  const totalTimeLogged = useMemo(() => {
    return timeLogs.reduce((sum, log) => sum + (log.duration_minutes ?? 0), 0);
  }, [timeLogs]);

  const isOverdue = useMemo(() => {
    return (
      jobDetail &&
      jobDetail.due_date &&
      new Date(jobDetail.due_date) < new Date() &&
      jobDetail.job_status?.name !== 'Completed'
    );
  }, [jobDetail]);

  useEffect(() => {
    if (jobId) {
      void fetchJobDetails(jobId);
      void fetchComments(jobId, { limit: 50, offset: 0 });
      void fetchAttachments(jobId, { limit: 50, offset: 0 });
      void fetchTimeLogs({ job_id: jobId, limit: 50, offset: 0 });
      void fetchChecklists({ job_id: jobId, limit: 50, offset: 0 });
      void fetchChecklistItems({ limit: 100, offset: 0 });
      void fetchJobHistory(jobId, { limit: 50, offset: 0 });
      void fetchSubJobs({ limit: 20, offset: 0 });
      void fetchUsers({ limit: 100, offset: 0, is_active: true });
      void fetchTags({ limit: 100, offset: 0 });
      void fetchJobStatuses({ limit: 50, offset: 0, is_active: true });
    }
  }, [jobId, fetchJobDetails, fetchComments, fetchAttachments, fetchTimeLogs, fetchChecklists, fetchChecklistItems, fetchJobHistory, fetchSubJobs, fetchUsers, fetchTags, fetchJobStatuses]);

  useEffect(() => {
    if (jobDetail && editModalVisible) {
      editForm.setFieldsValue({
        title: jobDetail.title,
        description: jobDetail.description,
        job_priority_id: jobDetail.job_priority_id,
        due_date: jobDetail.due_date ? dayjs(jobDetail.due_date) : null,
        department_id: jobDetail.department_id
      });
    }
  }, [jobDetail, editModalVisible, editForm]);

  const handleBack = useCallback(() => {
    navigate(ROUTES.JOBS);
  }, [navigate]);

  const handleEditJob = useCallback(async () => {
    if (!jobId) return;
    try {
      const values = await editForm.validateFields();
      if (values.title && values.title.length < 5) {
        messageApi.error('Title must be at least 5 characters');
        return;
      }
      await JobsService.patch(jobId, {
        ...values,
        due_date: values.due_date ? (values.due_date as Dayjs).toISOString() : null
      });
      messageApi.success('Job updated successfully');
      setEditModalVisible(false);
      editForm.resetFields();
      void fetchJobDetails(jobId);
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [jobId, editForm, messageApi, fetchJobDetails]);

  const handleAssignJob = useCallback(async () => {
    if (!jobId) return;
    try {
      const values = await assignForm.validateFields();
      if (!values.assigned_to_user_id) {
        messageApi.error('Please select a user');
        return;
      }
      await JobsService.createAssign(jobId, { assigned_to_user_id: values.assigned_to_user_id });
      messageApi.success('Job assigned successfully');
      setAssignModalVisible(false);
      assignForm.resetFields();
      void fetchJobDetails(jobId);
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [jobId, assignForm, messageApi, fetchJobDetails]);

  const handleChangeStatus = useCallback(
    async (statusId: string) => {
      if (!jobId) return;
      Modal.confirm({
        title: 'Change Status',
        content: 'Are you sure you want to change the job status?',
        onOk: async () => {
          try {
            await JobsService.createStatus(jobId, { job_status_id: statusId });
            messageApi.success('Status updated successfully');
            void fetchJobDetails(jobId);
          } catch (e) {
            const { message: errorMessage } = parseError(e);
            messageApi.error(errorMessage);
          }
        }
      });
    },
    [jobId, messageApi, fetchJobDetails]
  );

  const handleCancelJob = useCallback(async () => {
    if (!jobId) return;
    Modal.confirm({
      title: 'Cancel Job',
      content: 'Are you sure you want to cancel this job?',
      okText: 'Confirm Cancel',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await JobsService.createCancel(jobId);
          messageApi.warning('Job cancelled');
          setCancelModalVisible(false);
          void fetchJobDetails(jobId);
        } catch (e) {
          const { message: errorMessage } = parseError(e);
          messageApi.error(errorMessage);
        }
      }
    });
  }, [jobId, messageApi, fetchJobDetails]);

  const handleReopenJob = useCallback(async () => {
    if (!jobId) return;
    Modal.confirm({
      title: 'Reopen Job',
      content: 'Are you sure you want to reopen this job?',
      onOk: async () => {
        try {
          await JobsService.createReopen(jobId);
          messageApi.success('Job reopened successfully');
          setReopenModalVisible(false);
          void fetchJobDetails(jobId);
        } catch (e) {
          const { message: errorMessage } = parseError(e);
          messageApi.error(errorMessage);
        }
      }
    });
  }, [jobId, messageApi, fetchJobDetails]);

  const handlePostComment = useCallback(async () => {
    if (!jobId || !currentUser) return;
    try {
      const values = await commentForm.validateFields();
      if (!values.content) {
        messageApi.error('Comment cannot be empty');
        return;
      }
      if (values.content.length > 5000) {
        messageApi.error('Comment must be less than 5000 characters');
        return;
      }
      await JobsService.createComments({
        job_id: jobId,
        content: values.content,
        user_id: currentUser.id
      });
      messageApi.success('Comment added');
      commentForm.resetFields();
      void fetchComments(jobId, { limit: 50, offset: 0 });
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [jobId, currentUser, commentForm, messageApi, fetchComments]);

  const handleDeleteComment = useCallback(
    async (commentId: string) => {
      Modal.confirm({
        title: 'Delete Comment',
        content: 'Are you sure you want to delete this comment?',
        onOk: async () => {
          try {
            await JobsService.deleteCommentsById(commentId);
            messageApi.success('Comment deleted');
            if (jobId) {
              void fetchComments(jobId, { limit: 50, offset: 0 });
            }
          } catch (e) {
            const { message: errorMessage } = parseError(e);
            messageApi.error(errorMessage);
          }
        }
      });
    },
    [jobId, messageApi, fetchComments]
  );

  const handleUploadAttachment = useCallback(
    async (file: File) => {
      if (!jobId || !currentUser) return;
      try {
        await JobsService.createAttachments({
          job_id: jobId,
          file_name: file.name,
          file_path: '',
          file_type: file.type,
          file_size: file.size,
          uploaded_by_user_id: currentUser.id
        });
        messageApi.success('File uploaded successfully');
        void fetchAttachments(jobId, { limit: 50, offset: 0 });
      } catch (e) {
        const { message: errorMessage } = parseError(e);
        messageApi.error(errorMessage);
      }
      return false;
    },
    [jobId, currentUser, messageApi, fetchAttachments]
  );

  const handleDeleteAttachment = useCallback(
    async (attachmentId: string) => {
      Modal.confirm({
        title: 'Delete Attachment',
        content: 'Are you sure you want to delete this attachment?',
        onOk: async () => {
          try {
            await JobsService.deleteAttachmentsById(attachmentId);
            messageApi.success('Attachment deleted');
            if (jobId) {
              void fetchAttachments(jobId, { limit: 50, offset: 0 });
            }
          } catch (e) {
            const { message: errorMessage } = parseError(e);
            messageApi.error(errorMessage);
          }
        }
      });
    },
    [jobId, messageApi, fetchAttachments]
  );

  const handleLogTime = useCallback(async () => {
    if (!jobId || !currentUser) return;
    try {
      const values = await timeLogForm.validateFields();
      if (!values.start_time) {
        messageApi.error('Start time is required');
        return;
      }
      if (!values.end_time) {
        messageApi.error('End time is required');
        return;
      }
      await TimeLogsService.create({
        job_id: jobId,
        user_id: currentUser.id,
        start_time: (values.start_time as Dayjs).toISOString(),
        end_time: (values.end_time as Dayjs).toISOString(),
        notes: values.notes
      });
      messageApi.success('Time logged successfully');
      setTimeLogModalVisible(false);
      timeLogForm.resetFields();
      void fetchTimeLogs({ job_id: jobId, limit: 50, offset: 0 });
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [jobId, currentUser, timeLogForm, messageApi, fetchTimeLogs]);

  const handleStartTimer = useCallback(async () => {
    if (!jobId) return;
    try {
      const response = await TimeLogsService.createStart({ job_id: jobId, notes: null });
      setActiveTimerLogId(response.data.id);
      messageApi.info('Timer started');
      void fetchTimeLogs({ job_id: jobId, limit: 50, offset: 0 });
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [jobId, messageApi, fetchTimeLogs]);

  const handleStopTimer = useCallback(async () => {
    if (!activeTimerLogId) return;
    try {
      await TimeLogsService.createStop(activeTimerLogId, { notes: null });
      messageApi.success('Timer stopped');
      setActiveTimerLogId(null);
      if (jobId) {
        void fetchTimeLogs({ job_id: jobId, limit: 50, offset: 0 });
      }
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [activeTimerLogId, jobId, messageApi, fetchTimeLogs]);

  const handleCreateChecklist = useCallback(async () => {
    if (!jobId) return;
    try {
      const values = await checklistForm.validateFields();
      if (!values.title) {
        messageApi.error('Checklist title is required');
        return;
      }
      await ChecklistsService.create({
        job_id: jobId,
        title: values.title,
        description: values.description,
        display_order: 0
      });
      messageApi.success('Checklist created');
      checklistForm.resetFields();
      void fetchChecklists({ job_id: jobId, limit: 50, offset: 0 });
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [jobId, checklistForm, messageApi, fetchChecklists]);

  const handleCreateChecklistItem = useCallback(
    async (checklistId: string) => {
      try {
        const values = await checklistItemForm.validateFields();
        if (!values.description) {
          messageApi.error('Item description is required');
          return;
        }
        await ChecklistsService.createItems({
          checklist_id: checklistId,
          description: values.description,
          is_completed: false,
          display_order: 0
        });
        messageApi.success('Item added');
        checklistItemForm.resetFields();
        void fetchChecklistItems({ limit: 100, offset: 0 });
      } catch (e) {
        const { message: errorMessage } = parseError(e);
        messageApi.error(errorMessage);
      }
    },
    [checklistItemForm, messageApi, fetchChecklistItems]
  );

  const handleToggleChecklistItem = useCallback(
    async (itemId: string, isCompleted: boolean) => {
      try {
        await ChecklistsService.updateItemsById(itemId, { is_completed: !isCompleted });
        void fetchChecklistItems({ limit: 100, offset: 0 });
      } catch (e) {
        const { message: errorMessage } = parseError(e);
        messageApi.error(errorMessage);
      }
    },
    [messageApi, fetchChecklistItems]
  );

  const handleAddTag = useCallback(
    async (tagId: string) => {
      if (!jobId) return;
      try {
        await JobsService.createTags({ job_id: jobId, tag_id: tagId });
        messageApi.success('Tag added');
        setTagPopoverVisible(false);
        void fetchJobDetails(jobId);
      } catch (e) {
        const { message: errorMessage } = parseError(e);
        messageApi.error(errorMessage);
      }
    },
    [jobId, messageApi, fetchJobDetails]
  );

  const handleRemoveTag = useCallback(
    async (jobTagId: string) => {
      try {
        await JobsService.deleteTagsById(jobTagId);
        messageApi.success('Tag removed');
        if (jobId) {
          void fetchJobDetails(jobId);
        }
      } catch (e) {
        const { message: errorMessage } = parseError(e);
        messageApi.error(errorMessage);
      }
    },
    [jobId, messageApi, fetchJobDetails]
  );

  const handleCreateSubJob = useCallback(async () => {
    if (!jobId) return;
    try {
      const values = await subJobForm.validateFields();
      if (!values.title) {
        messageApi.error('Sub-job title is required');
        return;
      }
      await JobsService.create({
        ...values,
        parent_job_id: jobId
      });
      messageApi.success('Sub-job created');
      setSubJobModalVisible(false);
      subJobForm.resetFields();
      void fetchSubJobs({ limit: 20, offset: 0 });
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [jobId, subJobForm, messageApi, fetchSubJobs]);

  const statusMenu = useMemo(() => {
    return {
      items: jobStatuses.map((status) => ({
        key: status.id,
        label: status.name,
        onClick: () => void handleChangeStatus(status.id)
      }))
    };
  }, [jobStatuses, handleChangeStatus]);

  const attachmentColumns = useMemo(
    () => [
      {
        title: 'File Name',
        dataIndex: 'file_name',
        key: 'file_name'
      },
      {
        title: 'Size',
        dataIndex: 'file_size',
        key: 'file_size',
        render: (size: number) => `${(size / 1024).toFixed(2)} KB`,
        responsive: ['md'] as ('md' | 'lg' | 'xl')[]
      },
      {
        title: 'Uploaded',
        dataIndex: 'created_at',
        key: 'created_at',
        render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm'),
        responsive: ['lg'] as ('md' | 'lg' | 'xl')[]
      },
      {
        title: 'Actions',
        key: 'actions',
        render: (_: unknown, record: Attachment) => (
          <Button
            type="text"
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => void handleDeleteAttachment(record.id)}
          >
            {screens.md ? 'Delete' : ''}
          </Button>
        )
      }
    ],
    [handleDeleteAttachment, screens]
  );

  const timeLogsColumns = useMemo(
    () => [
      {
        title: 'Start',
        dataIndex: 'start_time',
        key: 'start_time',
        render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm')
      },
      {
        title: 'End',
        dataIndex: 'end_time',
        key: 'end_time',
        render: (date: string | null) => (date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '—'),
        responsive: ['md'] as ('md' | 'lg' | 'xl')[]
      },
      {
        title: 'Duration',
        dataIndex: 'duration_minutes',
        key: 'duration_minutes',
        render: (minutes: number | null) => (minutes ? `${minutes} min` : '—')
      },
      {
        title: 'Notes',
        dataIndex: 'notes',
        key: 'notes',
        render: (notes: string | null) => notes ?? '—',
        responsive: ['lg'] as ('md' | 'lg' | 'xl')[]
      }
    ],
    []
  );

  const padding = screens.xs ? 12 : 24;

  if (jobLoading) {
    return (
      <div style={{ minHeight: '100vh', padding, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        {contextHolder}
        <Spin size="large" />
      </div>
    );
  }

  if (jobError) {
    return (
      <div style={{ minHeight: '100vh', padding }}>
        {contextHolder}
        <Alert
          type="error"
          message="Failed to load job details"
          description={parseError(jobError).message}
          showIcon
        />
      </div>
    );
  }

  if (!jobDetail) {
    return (
      <div style={{ minHeight: '100vh', padding }}>
        {contextHolder}
        <Alert type="warning" message="Job not found" showIcon />
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', width: '100%', padding, backgroundColor: '#f5f5f5' }}>
      {contextHolder}

      <Card
        bordered={false}
        style={{
          marginBottom: 24,
          borderRadius: 6,
          boxShadow: '0 1px 2px rgba(0,0,0,0.06)'
        }}
      >
        <Row gutter={[16, 16]} align="middle" justify="space-between" style={{ marginBottom: 16 }}>
          <Col xs={24} md={12}>
            <Button type="text" icon={<ArrowLeftOutlined />} onClick={handleBack}>
              Back to Jobs
            </Button>
          </Col>
          <Col xs={24} md={12}>
            <Space wrap style={{ width: '100%', justifyContent: screens.md ? 'flex-end' : 'flex-start' }}>
              <Button type="default" icon={<EditOutlined />} onClick={() => setEditModalVisible(true)}>
                Edit
              </Button>
              <Button type="default" icon={<UserAddOutlined />} onClick={() => setAssignModalVisible(true)}>
                Assign
              </Button>
              <Button type="primary" onClick={() => statusMenu.items.length > 0 && statusMenu.items[0].onClick?.()}>
                Change Status
              </Button>
              <Button danger icon={<CloseCircleOutlined />} onClick={() => setCancelModalVisible(true)}>
                Cancel
              </Button>
              <Button type="default" icon={<UndoOutlined />} onClick={() => setReopenModalVisible(true)}>
                Reopen
              </Button>
            </Space>
          </Col>
        </Row>

        <div>
          <Typography.Text type="secondary" copyable style={{ fontSize: 12 }}>
            {jobDetail.id}
          </Typography.Text>
          <Typography.Title level={3} style={{ margin: '4px 0 0 0' }}>
            {jobDetail.title}
          </Typography.Title>
        </div>
      </Card>

      <Row gutter={[24, 24]}>
        <Col xs={24} lg={8}>
          <Card bordered={false} title="Job Information">
            <Space direction="vertical" size="small" style={{ width: '100%' }}>
              <Tag color="blue" style={{ fontSize: 14, padding: '4px 12px' }}>
                {jobDetail.job_status?.name ?? '—'}
              </Tag>
              <Tag color="orange" style={{ fontSize: 14, padding: '4px 12px' }}>
                {jobDetail.job_priority?.name ?? '—'}
              </Tag>
            </Space>

            <Descriptions column={1} size="small" bordered={false} style={{ marginTop: 16 }}>
              <Descriptions.Item label="Job Type">{jobDetail.job_type?.name ?? '—'}</Descriptions.Item>
              <Descriptions.Item label="Created By">
                {jobDetail.created_by_user?.first_name ?? ''} {jobDetail.created_by_user?.last_name ?? ''}
              </Descriptions.Item>
              <Descriptions.Item label="Assignee">
                {jobDetail.assigned_to_user
                  ? `${jobDetail.assigned_to_user.first_name ?? ''} ${jobDetail.assigned_to_user.last_name ?? ''}`
                  : '—'}
              </Descriptions.Item>
              <Descriptions.Item label="Department">{jobDetail.department?.name ?? '—'}</Descriptions.Item>
              <Descriptions.Item label="Due Date">
                {jobDetail.due_date ? dayjs(jobDetail.due_date).format('YYYY-MM-DD') : '—'}
              </Descriptions.Item>
              <Descriptions.Item label="Created">{dayjs(jobDetail.created_at).format('YYYY-MM-DD HH:mm')}</Descriptions.Item>
              <Descriptions.Item label="Last Updated">{dayjs(jobDetail.updated_at).format('YYYY-MM-DD HH:mm')}</Descriptions.Item>
              <Descriptions.Item label="Total Time Logged">{totalTimeLogged} min</Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid #f0f0f0' }}>
              <Typography.Text strong>Tags</Typography.Text>
              <Space wrap size="small" style={{ marginTop: 8 }}>
                {(jobDetail.job_tags ?? []).map((jobTag) => (
                  <Tag
                    key={jobTag.id}
                    closable
                    onClose={() => void handleRemoveTag(jobTag.id)}
                    color={jobTag.tag?.color ?? undefined}
                  >
                    {jobTag.tag?.name ?? ''}
                  </Tag>
                ))}
                <Popover
                  content={
                    <Space direction="vertical">
                      {availableTags.map((tag) => (
                        <Button
                          key={tag.id}
                          type="link"
                          size="small"
                          onClick={() => void handleAddTag(tag.id)}
                          style={{ color: tag.color ?? undefined }}
                        >
                          {tag.name}
                        </Button>
                      ))}
                    </Space>
                  }
                  trigger="click"
                  open={tagPopoverVisible}
                  onOpenChange={setTagPopoverVisible}
                >
                  <Button type="dashed" size="small" icon={<PlusOutlined />}>
                    Add Tag
                  </Button>
                </Popover>
              </Space>
            </div>
          </Card>
        </Col>

        <Col xs={24} lg={16}>
          <Card bordered={false}>
            <Tabs activeKey={activeTab} onChange={setActiveTab} type="card">
              <Tabs.TabPane tab="Description" key="description">
                <Typography.Paragraph style={{ whiteSpace: 'pre-wrap', lineHeight: '1.8' }}>
                  {jobDetail.description ?? 'No description provided.'}
                </Typography.Paragraph>
              </Tabs.TabPane>

              <Tabs.TabPane tab="Checklists" key="checklists">
                <List
                  dataSource={checklists}
                  renderItem={(checklist) => {
                    const items = checklistItems.filter((item) => item.checklist_id === checklist.id);
                    const completedCount = items.filter((item) => item.is_completed).length;
                    const progress = items.length > 0 ? (completedCount / items.length) * 100 : 0;

                    return (
                      <List.Item>
                        <div style={{ width: '100%' }}>
                          <Typography.Text strong>{checklist.title}</Typography.Text>
                          <Progress percent={Math.round(progress)} size="small" style={{ marginTop: 8 }} />
                          <List
                            dataSource={items}
                            renderItem={(item) => (
                              <List.Item>
                                <Checkbox
                                  checked={item.is_completed}
                                  onChange={() => void handleToggleChecklistItem(item.id, item.is_completed)}
                                >
                                  {item.description}
                                </Checkbox>
                              </List.Item>
                            )}
                          />
                        </div>
                      </List.Item>
                    );
                  }}
                />
                <Button type="dashed" icon={<PlusOutlined />} block style={{ marginTop: 12 }} onClick={() => void handleCreateChecklist()}>
                  Add Checklist
                </Button>
              </Tabs.TabPane>

              <Tabs.TabPane tab="Comments" key="comments">
                <List
                  dataSource={comments}
                  renderItem={(comment) => (
                    <List.Item
                      actions={[
                        <Button
                          key="delete"
                          type="text"
                          danger
                          size="small"
                          icon={<DeleteOutlined />}
                          onClick={() => void handleDeleteComment(comment.id)}
                        >
                          Delete
                        </Button>
                      ]}
                    >
                      <List.Item.Meta
                        title={`User ${comment.user_id}`}
                        description={dayjs(comment.created_at).format('YYYY-MM-DD HH:mm')}
                      />
                      <div>{comment.content}</div>
                    </List.Item>
                  )}
                />
                <Form form={commentForm} layout="vertical" style={{ marginTop: 16 }}>
                  <Form.Item name="content" label="Add a comment">
                    <Input.TextArea rows={3} placeholder="Write a comment..." maxLength={5000} showCount />
                  </Form.Item>
                  <Button type="primary" icon={<SendOutlined />} onClick={handlePostComment} style={{ marginTop: 8 }}>
                    Post Comment
                  </Button>
                </Form>
              </Tabs.TabPane>

              <Tabs.TabPane tab="Attachments" key="attachments">
                <Upload.Dragger
                  beforeUpload={(file) => {
                    void handleUploadAttachment(file);
                    return false;
                  }}
                  accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.gif,.zip"
                  multiple
                  style={{ marginBottom: 16 }}
                >
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">Click or drag file to upload</p>
                </Upload.Dragger>
                <Table
                  dataSource={attachments}
                  columns={attachmentColumns}
                  size="small"
                  pagination={false}
                  rowKey="id"
                  scroll={{ x: 'max-content' }}
                />
              </Tabs.TabPane>

              <Tabs.TabPane tab="Time Logs" key="timelogs">
                <Row gutter={[16, 16]} align="middle" justify="space-between" style={{ marginBottom: 16 }}>
                  <Col xs={24} sm={12}>
                    <Statistic title="Total Time" value={totalTimeLogged} suffix="min" />
                  </Col>
                  <Col xs={24} sm={12}>
                    <Space wrap style={{ width: '100%', justifyContent: screens.sm ? 'flex-end' : 'flex-start' }}>
                      <Button type="primary" icon={<ClockCircleOutlined />} onClick={() => setTimeLogModalVisible(true)}>
                        Log Time
                      </Button>
                      {!activeTimerLogId ? (
                        <Button type="default" icon={<PlayCircleOutlined />} onClick={handleStartTimer}>
                          Start Timer
                        </Button>
                      ) : (
                        <Button type="default" danger icon={<PauseCircleOutlined />} onClick={handleStopTimer}>
                          Stop Timer
                        </Button>
                      )}
                    </Space>
                  </Col>
                </Row>
                <Table
                  dataSource={timeLogs}
                  columns={timeLogsColumns}
                  size="small"
                  pagination={false}
                  rowKey="id"
                  scroll={{ x: 'max-content' }}
                />
              </Tabs.TabPane>

              <Tabs.TabPane tab="History" key="history">
                <Timeline mode="left">
                  {jobHistory.map((entry) => (
                    <Timeline.Item key={entry.id}>
                      <Typography.Text strong>{entry.action_type}</Typography.Text>
                      <br />
                      <Typography.Text type="secondary">{dayjs(entry.created_at).format('YYYY-MM-DD HH:mm')}</Typography.Text>
                      {entry.field_name && (
                        <div>
                          <Typography.Text>
                            {entry.field_name}: {entry.old_value ?? '—'} → {entry.new_value ?? '—'}
                          </Typography.Text>
                        </div>
                      )}
                    </Timeline.Item>
                  ))}
                </Timeline>
              </Tabs.TabPane>
            </Tabs>
          </Card>
        </Col>
      </Row>

      <Card bordered={false} title="Sub-Jobs" size="small" style={{ marginTop: 24 }}>
        <List
          grid={{ gutter: 16, column: screens.lg ? 3 : screens.md ? 2 : 1 }}
          dataSource={subJobs}
          renderItem={(subJob) => (
            <List.Item>
              <Card size="small">
                <Typography.Text strong>{subJob.title}</Typography.Text>
                <br />
                <Typography.Text type="secondary">{dayjs(subJob.created_at).format('YYYY-MM-DD')}</Typography.Text>
              </Card>
            </List.Item>
          )}
        />
        <Button type="dashed" icon={<PlusOutlined />} onClick={() => setSubJobModalVisible(true)} style={{ marginTop: 12 }}>
          Add Sub-Job
        </Button>
      </Card>

      <Modal
        title="Edit Job"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        onOk={handleEditJob}
        width={640}
        okText="Save Changes"
      >
        <Form form={editForm} layout="vertical">
          <Form.Item name="title" label="Title" rules={[{ required: true, message: 'Title is required' }]}>
            <Input placeholder="Job title" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={4} placeholder="Job description" />
          </Form.Item>
          <Form.Item name="job_priority_id" label="Priority">
            <Select placeholder="Select priority" />
          </Form.Item>
          <Form.Item name="due_date" label="Due Date">
            <DatePicker showTime style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="department_id" label="Department">
            <Select placeholder="Select department" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Assign Job"
        open={assignModalVisible}
        onCancel={() => setAssignModalVisible(false)}
        onOk={handleAssignJob}
        width={480}
        okText="Assign"
      >
        <Form form={assignForm}>
          <Form.Item
            name="assigned_to_user_id"
            label="Select User"
            rules={[{ required: true, message: 'Please select a user' }]}
          >
            <Select showSearch placeholder="Search and select user" filterOption optionFilterProp="label">
              {users.map((user) => (
                <Select.Option key={user.id} value={user.id} label={`${user.first_name} ${user.last_name}`}>
                  {user.first_name} {user.last_name} ({user.email})
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Cancel Job"
        open={cancelModalVisible}
        onCancel={() => setCancelModalVisible(false)}
        onOk={handleCancelJob}
        width={480}
        okText="Confirm Cancel"
        okButtonProps={{ danger: true }}
      >
        <Input.TextArea rows={3} placeholder="Please provide a reason for cancelling this job" />
      </Modal>

      <Modal
        title="Reopen Job"
        open={reopenModalVisible}
        onCancel={() => setReopenModalVisible(false)}
        onOk={handleReopenJob}
        width={480}
        okText="Confirm Reopen"
      >
        <Typography.Paragraph>Are you sure you want to reopen this job?</Typography.Paragraph>
      </Modal>

      <Modal
        title="Log Time"
        open={timeLogModalVisible}
        onCancel={() => setTimeLogModalVisible(false)}
        onOk={handleLogTime}
        width={520}
        okText="Save Time Log"
      >
        <Form form={timeLogForm} layout="vertical">
          <Form.Item name="start_time" label="Start Time" rules={[{ required: true, message: 'Start time is required' }]}>
            <DatePicker showTime style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="end_time" label="End Time" rules={[{ required: true, message: 'End time is required' }]}>
            <DatePicker showTime style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="notes" label="Notes">
            <Input.TextArea rows={2} placeholder="Optional notes" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Create Sub-Job"
        open={subJobModalVisible}
        onCancel={() => setSubJobModalVisible(false)}
        onOk={handleCreateSubJob}
        width={600}
        okText="Create Sub-Job"
      >
        <Form form={subJobForm} layout="vertical">
          <Form.Item name="title" label="Title" rules={[{ required: true, message: 'Sub-job title is required' }]}>
            <Input placeholder="Sub-job title" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} placeholder="Sub-job description" />
          </Form.Item>
          <Form.Item name="assigned_to_user_id" label="Assignee">
            <Select showSearch placeholder="Select assignee" allowClear>
              {users.map((user) => (
                <Select.Option key={user.id} value={user.id}>
                  {user.first_name} {user.last_name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="job_priority_id" label="Priority">
            <Select placeholder="Select priority" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Image Preview"
        open={imagePreviewVisible}
        onCancel={() => setImagePreviewVisible(false)}
        footer={null}
        width={720}
      >
        <img src={imagePreviewUrl} alt="Preview" style={{ width: '100%', maxWidth: '100%', objectFit: 'contain' }} />
      </Modal>
    </div>
  );
};

export default JobDetailPage;