import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Pencil, Trash2, Check, X, Copy } from 'lucide-react'
import {
  listGlobalRenderPositions,
  createGlobalRenderPosition,
  updateGlobalRenderPosition,
  deleteGlobalRenderPosition,
  type GlobalRenderPosition,
  type GlobalRenderPositionCreate,
} from '../../api/renderPositions'

interface EditState {
  id: string | null
  name: string
  rotation_x: number
  rotation_y: number
  rotation_z: number
  is_default: boolean
  sort_order: number
  focal_length_mm: number | null
  sensor_width_mm: number | null
}

const EMPTY_EDIT: EditState = {
  id: null,
  name: '',
  rotation_x: 0,
  rotation_y: 0,
  rotation_z: 0,
  is_default: false,
  sort_order: 0,
  focal_length_mm: null,
  sensor_width_mm: null,
}

export default function GlobalRenderPositionsPanel() {
  const qc = useQueryClient()
  const [editing, setEditing] = useState<EditState | null>(null)
  const [adding, setAdding] = useState(false)

  const { data: positions = [], isLoading } = useQuery({
    queryKey: ['global-render-positions'],
    queryFn: listGlobalRenderPositions,
  })

  const createMut = useMutation({
    mutationFn: (body: GlobalRenderPositionCreate) => createGlobalRenderPosition(body),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['global-render-positions'] }); setAdding(false); setEditing(null) },
  })

  const updateMut = useMutation({
    mutationFn: ({ id, body }: { id: string; body: Partial<GlobalRenderPositionCreate> }) =>
      updateGlobalRenderPosition(id, body),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['global-render-positions'] }); setEditing(null) },
  })

  const deleteMut = useMutation({
    mutationFn: (id: string) => deleteGlobalRenderPosition(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['global-render-positions'] }),
  })

  function startEdit(pos: GlobalRenderPosition) {
    setAdding(false)
    setEditing({
      id: pos.id,
      name: pos.name,
      rotation_x: pos.rotation_x,
      rotation_y: pos.rotation_y,
      rotation_z: pos.rotation_z,
      is_default: pos.is_default,
      sort_order: pos.sort_order,
      focal_length_mm: pos.focal_length_mm,
      sensor_width_mm: pos.sensor_width_mm,
    })
  }

  function saveEdit() {
    if (!editing) return
    if (editing.id) {
      const { id, ...body } = editing
      updateMut.mutate({ id, body })
    }
  }

  function saveNew() {
    if (!editing) return
    const { id, ...body } = editing
    createMut.mutate(body)
  }

  function startAdd() {
    setEditing({ ...EMPTY_EDIT, sort_order: positions.length })
    setAdding(true)
  }

  function cancelEdit() {
    setEditing(null)
    setAdding(false)
  }

  function renderEditFormGrid() {
    if (!editing) return null
    return (
      <div className="grid grid-cols-6 gap-x-4 gap-y-3">
        {/* Row 1: Name + Is Default */}
        <div className="col-span-4 flex flex-col gap-1">
          <label className="text-xs font-medium text-content-muted">Name</label>
          <input
            className="input text-sm"
            placeholder="e.g. Front View"
            value={editing.name}
            onChange={(e) => setEditing({ ...editing, name: e.target.value })}
          />
        </div>
        <div className="col-span-2 flex flex-col gap-1">
          <label className="text-xs font-medium text-content-muted">Is Default</label>
          <label className="flex items-center gap-2 h-[34px]">
            <input
              type="checkbox"
              checked={editing.is_default}
              onChange={(e) => setEditing({ ...editing, is_default: e.target.checked })}
            />
            <span className="text-sm text-content-secondary">Default position</span>
          </label>
        </div>

        {/* Row 2: Rotation X, Y, Z */}
        <div className="col-span-2 flex flex-col gap-1">
          <label className="text-xs font-medium text-content-muted">Rotation X°</label>
          <input
            type="number"
            step="5"
            className="input w-24 text-sm"
            value={editing.rotation_x}
            onChange={(e) => setEditing({ ...editing, rotation_x: parseFloat(e.target.value) || 0 })}
          />
        </div>
        <div className="col-span-2 flex flex-col gap-1">
          <label className="text-xs font-medium text-content-muted">Rotation Y°</label>
          <input
            type="number"
            step="5"
            className="input w-24 text-sm"
            value={editing.rotation_y}
            onChange={(e) => setEditing({ ...editing, rotation_y: parseFloat(e.target.value) || 0 })}
          />
        </div>
        <div className="col-span-2 flex flex-col gap-1">
          <label className="text-xs font-medium text-content-muted">Rotation Z°</label>
          <input
            type="number"
            step="5"
            className="input w-24 text-sm"
            value={editing.rotation_z}
            onChange={(e) => setEditing({ ...editing, rotation_z: parseFloat(e.target.value) || 0 })}
          />
        </div>

        {/* Row 3: Focal Length, Sensor Width, Sort Order */}
        <div className="col-span-2 flex flex-col gap-1">
          <label className="text-xs font-medium text-content-muted">Focal Length mm</label>
          <input
            type="number"
            step="1"
            placeholder="50"
            className="input w-24 text-sm"
            value={editing.focal_length_mm ?? ''}
            onChange={(e) => setEditing({ ...editing, focal_length_mm: e.target.value ? parseFloat(e.target.value) : null })}
          />
        </div>
        <div className="col-span-2 flex flex-col gap-1">
          <label className="text-xs font-medium text-content-muted">Sensor Width mm</label>
          <input
            type="number"
            step="0.1"
            placeholder="36"
            className="input w-24 text-sm"
            value={editing.sensor_width_mm ?? ''}
            onChange={(e) => setEditing({ ...editing, sensor_width_mm: e.target.value ? parseFloat(e.target.value) : null })}
          />
        </div>
        <div className="col-span-2 flex flex-col gap-1">
          <label className="text-xs font-medium text-content-muted">Sort Order</label>
          <input
            type="number"
            className="input w-24 text-sm"
            value={editing.sort_order}
            onChange={(e) => setEditing({ ...editing, sort_order: parseInt(e.target.value) || 0 })}
          />
        </div>
      </div>
    )
  }

  if (isLoading) return <p className="text-sm text-content-muted">Loading...</p>

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-xs text-content-muted">
          Global camera rotation presets applied to all products. Per-product positions take priority.
        </p>
        <button className="btn btn-sm btn-primary flex items-center gap-1" onClick={startAdd}>
          <Plus size={14} /> Add position
        </button>
      </div>

      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-border-light text-left text-xs text-content-muted">
            <th className="pb-1 pr-3">Name</th>
            <th className="pb-1 pr-3 text-center">Rot X°</th>
            <th className="pb-1 pr-3 text-center">Rot Y°</th>
            <th className="pb-1 pr-3 text-center">Rot Z°</th>
            <th className="pb-1 pr-3 text-center">Focal mm</th>
            <th className="pb-1 pr-3 text-center">Default</th>
            <th className="pb-1 pr-3 text-center">Order</th>
            <th className="pb-1" />
          </tr>
        </thead>
        <tbody>
          {/* Add new — expandable form at top */}
          {adding && editing && (
            <>
              <tr className="border-b border-border-light bg-status-success-bg">
                <td colSpan={8} className="px-6 py-5 border-l-4 border-status-success-text">
                  <div className="text-sm font-medium text-content-secondary mb-3">New Position</div>
                  {renderEditFormGrid()}
                  <div className="flex justify-end gap-2 mt-4 pt-3 border-t border-border-light">
                    <button className="btn btn-sm" onClick={cancelEdit}>
                      <X size={14} className="mr-1" /> Cancel
                    </button>
                    <button
                      className="btn btn-sm btn-primary"
                      onClick={saveNew}
                      disabled={createMut.isPending || !editing.name.trim()}
                    >
                      <Check size={14} className="mr-1" /> Create
                    </button>
                  </div>
                </td>
              </tr>
            </>
          )}

          {positions.map((pos) => {
            const isEditingThis = !adding && editing !== null && editing.id === pos.id
            return (
              <React.Fragment key={pos.id}>
                {/* Display row — always visible */}
                <tr className={`border-b border-border-light/50 hover:bg-surface-alt/30 ${isEditingThis ? 'bg-surface-hover' : ''}`}>
                  <td className="py-1.5 pr-3 font-medium">{pos.name}</td>
                  <td className="py-1.5 pr-3 text-center text-content-muted">{pos.rotation_x}</td>
                  <td className="py-1.5 pr-3 text-center text-content-muted">{pos.rotation_y}</td>
                  <td className="py-1.5 pr-3 text-center text-content-muted">{pos.rotation_z}</td>
                  <td className="py-1.5 pr-3 text-center text-content-muted">
                    {pos.focal_length_mm != null ? pos.focal_length_mm : <span className="opacity-40">50</span>}
                  </td>
                  <td className="py-1.5 pr-3 text-center">
                    {pos.is_default && <span className="text-accent text-xs font-medium">&#10003;</span>}
                  </td>
                  <td className="py-1.5 pr-3 text-center text-content-muted">{pos.sort_order}</td>
                  <td className="py-1.5 flex items-center gap-1">
                    <button className="btn btn-xs" onClick={() => startEdit(pos)}><Pencil size={12} /></button>
                    <button
                      className="btn btn-xs text-blue-500"
                      onClick={() => createMut.mutate({
                        name: `${pos.name} (copy)`,
                        rotation_x: pos.rotation_x,
                        rotation_y: pos.rotation_y,
                        rotation_z: pos.rotation_z,
                        is_default: false,
                        sort_order: pos.sort_order,
                        focal_length_mm: pos.focal_length_mm,
                        sensor_width_mm: pos.sensor_width_mm,
                      })}
                      disabled={createMut.isPending}
                      title="Duplicate"
                    >
                      <Copy size={12} />
                    </button>
                    <button
                      className="btn btn-xs text-red-500"
                      onClick={() => { if (confirm(`Delete "${pos.name}"?`)) deleteMut.mutate(pos.id) }}
                      disabled={deleteMut.isPending}
                    >
                      <Trash2 size={12} />
                    </button>
                  </td>
                </tr>

                {/* Expandable edit form row */}
                {isEditingThis && (
                  <tr>
                    <td colSpan={8} className="px-6 py-5 bg-surface-alt border-l-4 border-accent border-b-2 border-b-border-light">
                      {renderEditFormGrid()}
                      <div className="flex justify-end gap-2 mt-4 pt-3 border-t border-border-light">
                        <button className="btn btn-sm" onClick={cancelEdit}>
                          <X size={14} className="mr-1" /> Cancel
                        </button>
                        <button
                          className="btn btn-sm btn-primary"
                          onClick={saveEdit}
                          disabled={updateMut.isPending || !editing!.name.trim()}
                        >
                          <Check size={14} className="mr-1" /> Save
                        </button>
                      </div>
                    </td>
                  </tr>
                )}
              </React.Fragment>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}
