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

export function StoresPage() {
  const params = useParams();
  const instanceId = params.instanceId ? Number(params.instanceId) : undefined;
  const navigate = useNavigate();
  const [isCreating, setIsCreating] = useState(false);
  const [createTitle, setCreateTitle] = useState('Create Store');
  const [editingInstanceId, setEditingInstanceId] = useState<number | string | null>(null);
  const [editTitle, setEditTitle] = useState('Edit Store');
  const [refreshKey, setRefreshKey] = useState(0);

  if (instanceId != null) {
    return (
      <>
        <div className="w-full">
          <StoreDetail 
            instanceId={instanceId} 
            onBack={() => navigate('/stores')}
            onEdit={() => setEditingInstanceId(instanceId)}
          />
        </div>

        <Modal
          open={editingInstanceId != null}
          onClose={() => setEditingInstanceId(null)}
          title={editTitle}
          width="md"
        >
          {editingInstanceId != null && (
            <DynamicForm 
              client={storeClient} 
              activityId={STORE.activities.EDIT_STORE.uid}
              instanceId={editingInstanceId}
              initialActivityName="Edit Store"
              onSuccess={() => {
                setEditingInstanceId(null);
                setRefreshKey(k => k + 1);
              }}
              onCancel={() => setEditingInstanceId(null)}
              onActivityChange={setEditTitle}
            />
          )}
        </Modal>
      </>
    );
  }

  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)]">Location Spread</h3>
      </div>
      <div className="flex-1 relative bg-slate-50">
         <DailyLogMap />
      </div>
    </div>
  );

  return (
    <>
      <StoresView 
        mapComponent={mapComponent}
        refreshKey={refreshKey}
        onRowClick={(row) => {
          const id = row.instance_id as number | string | undefined;
          if (id != null) navigate(`/stores/${id}`);
        }} 
        headerActions={
          <Button size="sm" iconLeft={<Plus size={14} />} onClick={() => {
            setCreateTitle('Create Store');
            setIsCreating(true);
          }}>
            Create Store
          </Button>
        }
        rowActions={(row) => (
          <Button size="sm" variant="secondary" onClick={() => {
            setEditTitle('Edit Store');
            setEditingInstanceId(row.instance_id as string | number);
          }}>
            Edit
          </Button>
        )}
      />

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

      <Modal
        open={editingInstanceId != null}
        onClose={() => setEditingInstanceId(null)}
        title={editTitle}
        width="md"
      >
        {editingInstanceId != null && (
          <DynamicForm 
            client={storeClient} 
            activityId={STORE.activities.EDIT_STORE.uid}
            instanceId={editingInstanceId}
            initialActivityName="Edit Store"
            onSuccess={() => {
              setEditingInstanceId(null);
              setRefreshKey(k => k + 1);
            }}
            onCancel={() => setEditingInstanceId(null)}
            onActivityChange={setEditTitle}
          />
        )}
      </Modal>
    </>
  );
}
