"use client";

import { useState, useCallback, useRef } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Clapperboard, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { TakeListPanel } from "./TakeListPanel";
import { TakeEditorPanel, type FullTake } from "./TakeEditorPanel";
import { NewShootDayDialog } from "./NewShootDayDialog";
import { NewSetupDialog } from "./NewSetupDialog";

// ─── Types ────────────────────────────────────────────────────────────────────

interface Project {
  id: string;
  name: string;
  code: string;
}

// ─── Component ────────────────────────────────────────────────────────────────

interface Props {
  projects: Project[];
}

export function ShootLogClient({ projects }: Props) {
  const [projectId, setProjectId] = useState<string>(projects[0]?.id ?? "");
  const [selectedTakeId, setSelectedTakeId] = useState<string | null>(null);
  const [selectedSetupId, setSelectedSetupId] = useState<string | null>(null);

  // Dialog state
  const [newDayOpen, setNewDayOpen] = useState(false);
  const [newSetupDayId, setNewSetupDayId] = useState<string | null>(null);

  // Refresh token to force TakeListPanel to refetch
  const [refreshToken, setRefreshToken] = useState(0);
  const refresh = useCallback(() => setRefreshToken((t) => t + 1), []);

  // ── Fetch selected take ────────────────────────────────────────────────────
  const { data: takeData, isLoading: takeLoading } = useQuery<{ take: FullTake }>({
    queryKey: ["take", selectedTakeId],
    queryFn: async () => {
      const res = await fetch(`/api/shoot-log/takes/${selectedTakeId}`);
      if (!res.ok) throw new Error("Failed to load take");
      return res.json();
    },
    enabled: !!selectedTakeId,
    staleTime: 0,
  });

  const take = takeData?.take ?? null;

  // ── Fetch previous take (same setup, takeNumber - 1) ──────────────────────
  const prevTakeId = take?.setup.takes.find(
    (t) => t.takeNumber === (take?.takeNumber ?? 0) - 1
  )?.id;

  const { data: prevTakeData } = useQuery<{ take: FullTake }>({
    queryKey: ["take", prevTakeId],
    queryFn: async () => {
      const res = await fetch(`/api/shoot-log/takes/${prevTakeId}`);
      if (!res.ok) throw new Error("Failed to load previous take");
      return res.json();
    },
    enabled: !!prevTakeId,
    staleTime: 60_000,
  });

  const previousTake = prevTakeData?.take ?? null;

  // ── Navigation ─────────────────────────────────────────────────────────────
  const allTakesInSetup = take?.setup.takes ?? [];
  const currentIdx = allTakesInSetup.findIndex((t) => t.id === selectedTakeId);
  const prevTakeNav = currentIdx > 0 ? allTakesInSetup[currentIdx - 1] : null;
  const nextTakeNav = currentIdx < allTakesInSetup.length - 1 ? allTakesInSetup[currentIdx + 1] : null;

  // ── Actions ────────────────────────────────────────────────────────────────
  const createTake = useCallback(
    async (setupId: string, initialData?: object) => {
      const res = await fetch(`/api/shoot-log/setups/${setupId}/takes`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(initialData ?? {}),
      });
      if (!res.ok) throw new Error("Failed to create take");
      const { take } = await res.json();
      refresh();
      setSelectedTakeId(take.id);
      setSelectedSetupId(setupId);
    },
    [refresh]
  );

  const handleDuplicate = useCallback(async () => {
    if (!take) return;
    // Build initial data from current take (omit id, notes, attachments)
    const { id, takeNumber, attachments, setup, createdById, createdAt, updatedAt, ...rest } = take as FullTake & Record<string, unknown>;
    void id; void takeNumber; void attachments; void setup; void createdById; void createdAt; void updatedAt;

    // Increment clip name
    const clipName = incrementClipName(take.clipName);
    const initial = { ...rest, clipName, supervisorNotes: null, continuityNotes: null, vfxRequirements: null };

    await createTake(take.setupId, initial);
  }, [take, createTake]);

  const handleDelete = useCallback(async () => {
    if (!selectedTakeId) return;
    if (!confirm("Delete this take? This cannot be undone.")) return;
    await fetch(`/api/shoot-log/takes/${selectedTakeId}`, { method: "DELETE" });
    setSelectedTakeId(null);
    refresh();
  }, [selectedTakeId, refresh]);

  // ── Render ─────────────────────────────────────────────────────────────────
  if (!projectId) {
    return (
      <div className="flex flex-col items-center justify-center h-full gap-4 text-zinc-500">
        <Clapperboard className="h-12 w-12 text-zinc-700" />
        <p>No active projects found.</p>
      </div>
    );
  }

  return (
    <>
      {/* Project selector (top bar) */}
      <div className="flex items-center gap-3 px-4 py-3 border-b border-zinc-800 bg-zinc-900/60 shrink-0">
        <Clapperboard className="h-4 w-4 text-amber-400 shrink-0" />
        <span className="text-xs font-semibold text-zinc-400 uppercase tracking-wider">Shot Log</span>
        <div className="ml-2">
          <select
            value={projectId}
            onChange={(e) => {
              setProjectId(e.target.value);
              setSelectedTakeId(null);
              setSelectedSetupId(null);
              setRefreshToken((t) => t + 1);
            }}
            className="bg-zinc-800 border border-zinc-700 rounded-lg text-sm text-white px-3 py-1.5 focus:outline-none focus:border-amber-600"
          >
            {projects.map((p) => (
              <option key={p.id} value={p.id}>
                {p.code} — {p.name}
              </option>
            ))}
          </select>
        </div>

        {/* Keyboard hint */}
        <div className="ml-auto hidden lg:flex items-center gap-3 text-[10px] text-zinc-600">
          <span>← → navigate</span>
          <span>D duplicate</span>
          <span>N new take</span>
        </div>
      </div>

      {/* Split layout */}
      <div className="flex flex-1 overflow-hidden min-h-0">
        {/* Left panel */}
        <div className="w-72 xl:w-80 shrink-0 border-r border-zinc-800 overflow-hidden flex flex-col">
          <TakeListPanel
            projectId={projectId}
            selectedTakeId={selectedTakeId}
            refreshToken={refreshToken}
            onSelectTake={(takeId, setupId) => {
              setSelectedTakeId(takeId);
              setSelectedSetupId(setupId);
            }}
            onNewDay={() => setNewDayOpen(true)}
            onNewSetup={(dayId) => setNewSetupDayId(dayId)}
            onNewTake={(setupId) => createTake(setupId)}
          />
        </div>

        {/* Right panel */}
        <div className="flex-1 overflow-hidden flex flex-col">
          {takeLoading ? (
            <div className="flex items-center justify-center h-full">
              <Loader2 className="h-6 w-6 animate-spin text-zinc-500" />
            </div>
          ) : take ? (
            <TakeEditorPanel
              key={take.id}
              take={take}
              previousTake={previousTake}
              onPrev={prevTakeNav ? () => setSelectedTakeId(prevTakeNav.id) : null}
              onNext={nextTakeNav ? () => setSelectedTakeId(nextTakeNav.id) : null}
              onDuplicate={handleDuplicate}
              onNewTake={() => createTake(take.setupId)}
              onDelete={handleDelete}
              onAttachmentsChange={refresh}
            />
          ) : (
            <div className="flex flex-col items-center justify-center h-full gap-3 text-zinc-600">
              <Clapperboard className="h-10 w-10 text-zinc-700" />
              <p className="text-sm">Select a take or create a new shoot day</p>
            </div>
          )}
        </div>
      </div>

      {/* Dialogs */}
      <NewShootDayDialog
        projectId={projectId}
        open={newDayOpen}
        onOpenChange={setNewDayOpen}
        onCreate={refresh}
      />
      {newSetupDayId && (
        <NewSetupDialog
          shootDayId={newSetupDayId}
          open={!!newSetupDayId}
          onOpenChange={(o) => { if (!o) setNewSetupDayId(null); }}
          onCreated={() => {
            setNewSetupDayId(null);
            refresh();
          }}
        />
      )}
    </>
  );
}

/** Increment trailing number in clip name: A001_C002 → A001_C003 */
function incrementClipName(clipName: string | null | undefined): string | null {
  if (!clipName) return null;
  const match = clipName.match(/^(.*?)(\d+)$/);
  if (!match) return clipName;
  const [, prefix, numStr] = match;
  const next = String(Number(numStr) + 1).padStart(numStr.length, "0");
  return `${prefix}${next}`;
}
