'use client';

import { useState, useEffect } from 'react';
import DataTable from '@/components/admin/DataTable';
import DetailModal from '@/components/admin/DetailModal';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ArrowLeft, CheckSquare } from 'lucide-react';
import Link from 'next/link';
import { useUserTimezone } from '@/lib/hooks/use-user-timezone';

export default function TasksBrowserPage() {
  const tz = useUserTimezone();
  const [tasks, setTasks] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(50);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedTask, setSelectedTask] = useState<any>(null);
  const [modalOpen, setModalOpen] = useState(false);

  const fetchTasks = async (currentPage: number, search?: string, sortBy?: string, sortOrder?: string) => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams({
        limit: pageSize.toString(),
        offset: ((currentPage - 1) * pageSize).toString(),
      });
      
      if (search) params.append('search', search);
      if (sortBy) params.append('sort', sortBy);
      if (sortOrder) params.append('order', sortOrder);

      const response = await fetch(`/api/data/tasks?${params}`);
      const result = await response.json();
      
      setTasks(result.tasks || []);
      setTotalCount(result.pagination?.total || 0);
    } catch (error) {
      console.error('Failed to fetch tasks:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchTasks(page);
  }, [page]);

  const handleRowClick = (task: any) => {
    setSelectedTask(task);
    setModalOpen(true);
  };

  const columns = [
    {
      key: 'id',
      label: 'ID',
      sortable: true,
    },
    {
      key: 'title',
      label: 'Title',
      sortable: true,
      render: (value: string) => (
        <div className="font-medium max-w-md truncate" title={value}>{value}</div>
      ),
    },
    {
      key: 'status',
      label: 'Status',
      sortable: true,
    },
    {
      key: 'priority',
      label: 'Priority',
      sortable: true,
    },
    {
      key: 'assigned_resource_id',
      label: 'Assigned To',
      sortable: true,
    },
    {
      key: 'project_id',
      label: 'Project ID',
      sortable: true,
    },
    {
      key: 'estimated_hours',
      label: 'Est. Hours',
      render: (value: number) => (
        value ? value.toFixed(2) : '-'
      ),
    },
    {
      key: 'create_date_time',
      label: 'Created',
      sortable: true,
      render: (value: string) => (
        value ? new Date(value).toLocaleDateString(undefined, { timeZone: tz }) : '-'
      ),
    },
  ];

  const detailFields = [
    { key: 'id', label: 'ID' },
    { key: 'title', label: 'Title' },
    { key: 'description', label: 'Description' },
    { key: 'status', label: 'Status' },
    { key: 'priority', label: 'Priority' },
    { key: 'assigned_resource_id', label: 'Assigned Resource ID' },
    { key: 'assigned_resource_role_id', label: 'Assigned Role ID' },
    { key: 'department_id', label: 'Department ID' },
    { key: 'estimated_hours', label: 'Estimated Hours' },
    { key: 'remaining_hours', label: 'Remaining Hours' },
    { key: 'hours_to_be_scheduled', label: 'Hours to Schedule' },
    { key: 'start_date_time', label: 'Start Date' },
    { key: 'end_date_time', label: 'End Date' },
    { key: 'completed_date_time', label: 'Completed Date' },
    { key: 'create_date_time', label: 'Created Date' },
    { key: 'creator_resource_id', label: 'Creator ID' },
    { key: 'completed_by_resource_id', label: 'Completed By ID' },
    { key: 'project_id', label: 'Project ID' },
    { key: 'ticket_id', label: 'Ticket ID' },
    { key: 'task_type', label: 'Task Type' },
    { key: 'task_is_billable', label: 'Billable' },
    { key: 'task_number', label: 'Task Number' },
    { key: 'synced_at', label: 'Synced At' },
    { key: 'is_deleted', label: 'Is Deleted' },
  ];

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <Link href="/admin/data-browser">
            <Button variant="outline" size="sm" className="gap-2">
              <ArrowLeft className="w-4 h-4" />
              Back
            </Button>
          </Link>
          <div className="h-8 w-px bg-border" />
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-green-100 dark:bg-green-950">
              <CheckSquare className="w-5 h-5 text-green-600 dark:text-green-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold tracking-tight">Tasks</h1>
              <p className="text-sm text-muted-foreground">Manage and inspect task data</p>
            </div>
          </div>
        </div>
        <Badge variant="secondary" className="w-fit">
          {totalCount} total records
        </Badge>
      </div>

      {/* Data Table Card */}
      <Card className="border-none shadow-md">
        <CardHeader className="border-b bg-muted/30">
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg">All Tasks</CardTitle>
              <CardDescription className="mt-1">
                View and search through all tasks in the system
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6">
          <DataTable
            columns={columns}
            data={tasks}
            totalCount={totalCount}
            page={page}
            pageSize={pageSize}
            onPageChange={setPage}
            onSort={(column, direction) => fetchTasks(page, undefined, column, direction)}
            onSearch={(query) => fetchTasks(1, query)}
            onRowClick={handleRowClick}
            isLoading={isLoading}
          />
        </CardContent>
      </Card>

      {/* Detail Modal */}
      <DetailModal
        open={modalOpen}
        onOpenChange={setModalOpen}
        title={selectedTask?.title || 'Task Details'}
        data={selectedTask}
        fields={detailFields}
      />
    </div>
  );
}
