import { useNavigate, useParams } from 'react-router-dom';
import { Modal } from '../components/reusable';
import { CallsView } from '../components/rv';
import { CallDetail } 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 { ORDER_BOOKING } from '../api/config';
import { orderBookingClient } from '../api/clients';

export function CallsPage() {
  const params = useParams();
  const instanceId = params.instanceId ? Number(params.instanceId) : undefined;
  const navigate = useNavigate();
  const [isCreating, setIsCreating] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);
  const [activeActivity, setActiveActivity] = useState<{ id: string; name: string } | null>(null);
  const [isFabOpen, setIsFabOpen] = useState(false);
  const [miningLoading, setMiningLoading] = useState(false);
  const [miningPrefill, setMiningPrefill] = useState<Record<string, unknown> | undefined>();
  const [selectedRow, setSelectedRow] = useState<Record<string, any> | null>(null);

  const handlePotentialMiningClick = async () => {
    setMiningLoading(true);
    setMiningPrefill(undefined);
    try {
      const storeCode = selectedRow?.store_code || selectedRow?.code || selectedRow?.store?.store_code;

      if (!storeCode) {
        console.warn("Store code not found on selected row, proceeding anyway.");
      }

      const payload = {
        store_code: storeCode,
        instance_id: String(instanceId)
      };

      const response = await orderBookingClient.request<{ potential: { potential: any[] } }>(
        'POST',
        '/api/papi2/potential-mining',
        payload,
        { 'TemplateID': '146' }
      );

      const rawPotential = response.potential?.potential || [];
      const mappedPotential = rawPotential.map((row: any) => {
        const cat = row.product_category || row.product_category_ || row.category;
        return {
          ...row,
          product_category_: cat,
          product_category: cat,
          productcategory: cat,
          category: cat,
          product_category_1: cat
        };
      });

      setMiningPrefill({ potential: mappedPotential });
      setActiveActivity({ id: ORDER_BOOKING.activities.POTENTIAL_MINING.uid, name: 'Potential Mining' });
    } catch (e: any) {
      alert("Failed to fetch potential mining data: " + (e.message || "Unknown error"));
    } finally {
      setMiningLoading(false);
      setIsFabOpen(false);
    }
  };

  return (
    <>
      <CallsView
        refreshKey={refreshKey}
        onRowClick={(row) => {
          setSelectedRow(row);
          const id = row.instance_id as number | string | undefined;
          if (id != null) navigate(`/calls/${id}`);
        }}
        headerActions={
          <Button size="sm" iconLeft={<Plus size={14} />} onClick={() => setIsCreating(true)}>
            Log Visit
          </Button>
        }
      />

      <Modal
        open={isCreating}
        onClose={() => setIsCreating(false)}
        title="Log Visit"
        width="md"
      >
        <DynamicForm
          client={orderBookingClient}
          activityId={ORDER_BOOKING.activities.LOG_VISIT.uid}
          onSuccess={() => {
            setIsCreating(false);
            setRefreshKey(k => k + 1);
          }}
          onCancel={() => setIsCreating(false)}
        />
      </Modal>

      <Modal
        open={instanceId != null}
        onClose={() => { navigate(`/calls`); setIsFabOpen(false); }}
        title={instanceId != null ? `Call #${instanceId}` : undefined}
        width="lg"
      >
        {instanceId != null && (
          <>
            <CallDetail instanceId={instanceId} />
            <div className="absolute bottom-6 right-6 flex flex-col items-end gap-3 z-50">
              {isFabOpen && (
                <div className="flex flex-col gap-2 bg-white p-3 rounded-sm shadow-xl border border-border-subtle animate-in fade-in slide-in-from-bottom-2">
                  <Button size="sm" variant="secondary" onClick={handlePotentialMiningClick} disabled={miningLoading}>
                    {miningLoading ? 'Loading...' : 'Potential Mining'}
                  </Button>
                  <Button size="sm" onClick={() => { setActiveActivity({ id: ORDER_BOOKING.activities.PLACE_ORDER.uid, name: 'Place Order' }); setIsFabOpen(false); }}>
                    Place Order
                  </Button>
                </div>
              )}
              <Button size='fab'
                className="rounded-full shadow-xl flex items-center justify-center !p-0"
                onClick={() => setIsFabOpen(!isFabOpen)}
              >
                <Plus size={24} className={`transition-transform duration-200 ${isFabOpen ? "rotate-45" : ""}`} />
              </Button>
            </div>
          </>
        )}
      </Modal>

      <Modal
        open={activeActivity != null}
        onClose={() => setActiveActivity(null)}
        title={activeActivity?.name}
        width="md"
      >
        {activeActivity && instanceId != null && (
          <DynamicForm
            client={orderBookingClient}
            activityId={activeActivity.id}
            instanceId={instanceId}
            ignorePrefill={activeActivity.id === ORDER_BOOKING.activities.PLACE_ORDER.uid}
            customPrefillData={activeActivity.id === ORDER_BOOKING.activities.POTENTIAL_MINING.uid ? miningPrefill : undefined}
            onSuccess={() => {
              setActiveActivity(null);
              setRefreshKey(k => k + 1);
            }}
            onCancel={() => setActiveActivity(null)}
          />
        )}
      </Modal>
    </>
  );
}
