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

export function DailyLogsPage() {
  const params = useParams();
  const instanceId = params.instanceId ? Number(params.instanceId) : undefined;
  const navigate = useNavigate();
  const [isCreating, setIsCreating] = useState(false);
  const [createTitle, setCreateTitle] = useState('Punch In');
  const [punchOutInstanceId, setPunchOutInstanceId] = useState<number | string | null>(null);
  const [punchOutTitle, setPunchOutTitle] = useState('Punch Out');
  const [refreshKey, setRefreshKey] = useState(0);

  const mapComponent = (
    <div className="!bg-[var(--tiles-card-bg)] rounded-lg shadow-sm border border-gray-100 overflow-hidden flex flex-col h-full min-h-[320px]">
      <div className="px-5 py-4 border-b border-[var(--z-block-border)] flex items-center gap-2">
         <MapPin size={18} className="text-slate-400" />
         <h3 className="text-md font-semibold text-[var(--z-text-default)]">Activity Locations</h3>
      </div>
      <div className="flex-1 relative bg-slate-50">
         <DailyLogMap />
      </div>
    </div>
  );

  return (
    <>
      {instanceId == null && (
        <DailyLogsView 
          mapComponent={mapComponent}
          refreshKey={refreshKey}
          presetAlias="my_logs"
          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={() => {
              setCreateTitle('Punch In');
              setIsCreating(true);
            }}>
              Punch In
            </Button>
          }
          rowActions={(row) => {
            const state = String(row.current_state_name || row.current_state_name_ || row.current_state || row.status || '').toLowerCase();
            // Show only for Punched In, hide for Punched Out or others
            if (state.includes('out') || !state.includes('in')) return null;
            
            return (
              <Button size="sm" variant="secondary" onClick={() => {
                setPunchOutTitle('Punch Out');
                setPunchOutInstanceId(row.instance_id as string | number);
              }}>
                Punch Out
              </Button>
            );
          }}
        />
      )}

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

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

      {instanceId != null && (
        <div className="w-full">
          <DailyLogDetail 
             instanceId={instanceId}
             refreshKey={refreshKey}
             onPunchOut={() => setPunchOutInstanceId(instanceId)} 
             onBack={() => navigate('/daily')} 
          />
        </div>
      )}
    </>
  );
}
