'use client'

import * as React from 'react'
import { Button } from './button'
import { Label } from './label' 
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from './dialog'
import { PREDEFINED_SHAPES, ProfileShape, createCustomShape, canvasToSVGPath } from '@/lib/profile-shapes'
import { Separator } from './separator'
import { cn } from '@/lib/utils'

interface ShapeSelectorProps {
  selectedShape: ProfileShape
  onShapeChange: (shape: ProfileShape) => void
}

// Shape preview component
function ShapePreview({ shape, isSelected, onClick }: { 
  shape: ProfileShape
  isSelected: boolean
  onClick: () => void 
}) {
  const clipPath = shape.clipPath.value || (shape.clipPath.d ? `path('${shape.clipPath.d}')` : 'circle(50%)')
  
  return (
    <button
      onClick={onClick}
      className={cn(
        'w-16 h-16 border-2 transition-all hover:scale-105',
        isSelected ? 'border-primary' : 'border-border'
      )}
    >
      <div 
        className="w-full h-full bg-gradient-to-br from-primary/20 to-primary/5"
        style={{ clipPath }}
      />
    </button>
  )
}

// Canvas drawing interface for custom shapes
function CustomShapeDrawer({ onShapeCreated }: { onShapeCreated: (shape: ProfileShape) => void }) {
  const canvasRef = React.useRef<HTMLCanvasElement>(null)
  const [isDrawing, setIsDrawing] = React.useState(false)
  const [points, setPoints] = React.useState<{ x: number; y: number }[]>([])
  
  const startDrawing = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = canvasRef.current
    if (!canvas) return
    
    const rect = canvas.getBoundingClientRect()
    const x = e.clientX - rect.left
    const y = e.clientY - rect.top
    
    setIsDrawing(true)
    setPoints([{ x, y }])
    
    // Clear canvas and start new drawing
    const ctx = canvas.getContext('2d')
    if (ctx) {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.strokeStyle = '#3b82f6'
      ctx.lineWidth = 2
      ctx.lineCap = 'round'
      ctx.beginPath()
      ctx.moveTo(x, y)
    }
  }
  
  const draw = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!isDrawing) return
    
    const canvas = canvasRef.current
    if (!canvas) return
    
    const rect = canvas.getBoundingClientRect()
    const x = e.clientX - rect.left
    const y = e.clientY - rect.top
    
    const ctx = canvas.getContext('2d')
    if (ctx) {
      ctx.lineTo(x, y)
      ctx.stroke()
    }
    
    setPoints(prev => [...prev, { x, y }])
  }
  
  const finishDrawing = () => {
    if (!isDrawing) return
    
    const canvas = canvasRef.current
    if (!canvas) return
    
    setIsDrawing(false)
    
    // Close the path visually
    const ctx = canvas.getContext('2d')
    if (ctx && points.length > 0) {
      ctx.closePath()
      ctx.stroke()
    }
  }
  
  const handleCreateShape = () => {
    if (points.length < 3) return
    
    const canvas = canvasRef.current
    if (!canvas) return
    
    // Convert canvas points to SVG path
    const svgPath = canvasToSVGPath(points, canvas.width, canvas.height)
    const customShape = createCustomShape(svgPath)
    
    onShapeCreated(customShape)
  }
  
  const clearCanvas = () => {
    const canvas = canvasRef.current
    if (!canvas) return
    
    const ctx = canvas.getContext('2d')
    if (ctx) {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
    }
    setPoints([])
  }
  
  return (
    <div className="space-y-4">
      <div>
        <Label className="text-sm font-medium">Draw Custom Shape</Label>
        <p className="text-xs text-muted-foreground mt-1">
          Draw a shape by clicking and dragging. The shape will automatically close.
        </p>
      </div>
      
      <div className="border border-border rounded-lg overflow-hidden">
        <canvas
          ref={canvasRef}
          width={300}
          height={300}
          className="w-full h-[300px] bg-muted cursor-crosshair"
          onMouseDown={startDrawing}
          onMouseMove={draw}
          onMouseUp={finishDrawing}
          onMouseLeave={finishDrawing}
        />
      </div>
      
      <div className="flex gap-2">
        <Button 
          variant="outline" 
          onClick={clearCanvas}
          className="flex-1"
        >
          Clear
        </Button>
        <Button 
          onClick={handleCreateShape}
          disabled={points.length < 3}
          className="flex-1"
        >
          Use This Shape
        </Button>
      </div>
      
      {points.length > 0 && points.length < 3 && (
        <p className="text-xs text-muted-foreground">
          Draw at least 3 points to create a shape
        </p>
      )}
    </div>
  )
}

// Main shape selector component
export function ShapeSelector({ selectedShape, onShapeChange }: ShapeSelectorProps) {
  const [showCustomDrawer, setShowCustomDrawer] = React.useState(false)
  
  const handleCustomShapeCreated = (shape: ProfileShape) => {
    onShapeChange(shape)
    setShowCustomDrawer(false)
  }
  
  return (
    <div className="space-y-4">
      <Label className="text-sm font-medium">Profile Shape</Label>
      
      {/* Predefined Shapes */}
      <div className="grid grid-cols-5 gap-3">
        {PREDEFINED_SHAPES.map((shape) => (
          <ShapePreview
            key={shape.name}
            shape={shape}
            isSelected={selectedShape.name === shape.name}
            onClick={() => onShapeChange(shape)}
          />
        ))}
      </div>
      
      <Separator />
      
      {/* Custom Shape Section */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <div>
            <Label className="text-sm font-medium">Custom Shape</Label>
            <p className="text-xs text-muted-foreground">Draw your own profile shape</p>
          </div>
          
          <Dialog open={showCustomDrawer} onOpenChange={setShowCustomDrawer}>
            <DialogTrigger asChild>
              <Button variant="outline" size="sm">
                Draw Shape
              </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-md">
              <DialogHeader>
                <DialogTitle>Create Custom Shape</DialogTitle>
              </DialogHeader>
              <CustomShapeDrawer onShapeCreated={handleCustomShapeCreated} />
            </DialogContent>
          </Dialog>
        </div>
        
        {/* Show current custom shape if selected */}
        {selectedShape.type === 'custom' && (
          <div className="flex items-center gap-3 p-3 border border-border rounded-lg bg-muted/50">
            <div 
              className="w-12 h-12 bg-gradient-to-br from-primary/20 to-primary/5"
              style={{ clipPath: `path('${selectedShape.clipPath.d}')` }}
            />
            <div className="flex-1">
              <p className="text-sm font-medium">Custom Shape</p>
              <p className="text-xs text-muted-foreground">Your custom drawn shape</p>
            </div>
            <Button 
              variant="outline" 
              size="sm"
              onClick={() => setShowCustomDrawer(true)}
            >
              Edit
            </Button>
          </div>
        )}
      </div>
    </div>
  )
}
