import { useNavigate, useParams } from 'react-router-dom';
import { Modal } from '../components/reusable';
import { DailyLogsView } from '../components/rv';
import { DailyLogDetail } from '../components/dv';
import { useState } from 'react';
import { Button } from '../components/buttons/Button';
import { Plus } from 'lucide-react';
import { DynamicForm } from '../components/forms/DynamicForm';
import { DAILY_REPORTS } from '../api/config';
import { dailyReportsClient } from '../api/clients';

export function DailyLogsPage() {
  const { instanceId } = useParams();
  const navigate = useNavigate();
  const [isCreating, setIsCreating] = useState(false);
  const [punchOutInstanceId, setPunchOutInstanceId] = useState<number | string | null>(null);
  const [refreshKey, setRefreshKey] = useState(0);

  return (
    <>
      <DailyLogsView 
        refreshKey={refreshKey}
        onRowClick={(row) => {
          const id = row.instance_id as number | string | undefined;
          if (id != null) navigate(`/daily/${id}`);
        }} 
        headerActions={
          <Button size="sm" iconLeft={<Plus size={14} />} onClick={() => setIsCreating(true)}>
            Punch In
          </Button>
        }
        rowActions={(row) => (
          <Button size="sm" variant="secondary" onClick={() => setPunchOutInstanceId(row.instance_id as string | number)}>
            Punch Out
          </Button>
        )}
      />

      <Modal
        open={isCreating}
        onClose={() => setIsCreating(false)}
        title="Punch In"
        width="md"
      >
        <DynamicForm 
          client={dailyReportsClient} 
          activityId={DAILY_REPORTS.activities.INIT.uid}
          onSuccess={() => {
            setIsCreating(false);
            setRefreshKey(k => k + 1);
          }}
          onCancel={() => setIsCreating(false)}
        />
      </Modal>

      <Modal
        open={punchOutInstanceId != null}
        onClose={() => setPunchOutInstanceId(null)}
        title="Punch Out"
        width="md"
      >
        {punchOutInstanceId != null && (
          <DynamicForm 
            client={dailyReportsClient} 
            activityId={DAILY_REPORTS.activities.PUNCH_OUT.uid}
            instanceId={punchOutInstanceId}
            onSuccess={() => {
              setPunchOutInstanceId(null);
              setRefreshKey(k => k + 1);
            }}
            onCancel={() => setPunchOutInstanceId(null)}
          />
        )}
      </Modal>

      <Modal
        open={instanceId != null}
        onClose={() => navigate(`/daily`)}
        title={instanceId != null ? `Daily Log #${instanceId}` : undefined}
        width="lg"
      >
        {instanceId != null && <DailyLogDetail instanceId={instanceId} />}
      </Modal>
    </>
  );
}
