import { useStore, Model3D } from '../store/useStore'
import {
  Info,
  MapPin,
  Calendar,
  Navigation,
  Cpu,
  FileBox,
  Settings,
  Sun,
  Palette,
  CircleDot,
  Share2,
  Link,
  Mail,
  Copy,
  Check
} from 'lucide-react'
import { useState } from 'react'

interface SectionProps {
  title: string
  icon: React.ReactNode
  children: React.ReactNode
  defaultOpen?: boolean
}

function Section({ title, icon, children, defaultOpen = true }: SectionProps) {
  const [isOpen, setIsOpen] = useState(defaultOpen)

  return (
    <div className="border-b border-surface-100 last:border-b-0">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="w-full px-4 py-3 flex items-center justify-between hover:bg-surface-50 transition-colors"
      >
        <div className="flex items-center gap-2 text-surface-700 font-medium">
          {icon}
          <span>{title}</span>
        </div>
        <svg
          className={`w-4 h-4 text-surface-400 transition-transform ${isOpen ? 'rotate-180' : ''}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>
      {isOpen && <div className="px-4 pb-4">{children}</div>}
    </div>
  )
}

function MetadataItem({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
  return (
    <div className="flex items-start gap-3 py-2">
      <div className="text-surface-400 mt-0.5">{icon}</div>
      <div className="flex-1 min-w-0">
        <p className="text-xs text-surface-400 uppercase tracking-wide">{label}</p>
        <p className="text-sm text-surface-700 truncate">{value}</p>
      </div>
    </div>
  )
}

export function ViewerSidebar({ model }: { model: Model3D }) {
  const { settings, updateSettings } = useStore()
  const [copied, setCopied] = useState(false)

  const formatNumber = (num: number) => {
    if (num >= 1000000) return (num / 1000000).toFixed(2) + ' million'
    if (num >= 1000) return (num / 1000).toFixed(1) + 'K'
    return num.toString()
  }

  const handleCopyLink = () => {
    navigator.clipboard.writeText(window.location.href)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="p-4 border-b border-surface-100">
        <h2 className="font-display font-semibold text-lg text-surface-800 line-clamp-2">
          {model.name}
        </h2>
        {model.description && (
          <p className="text-sm text-surface-500 mt-1 line-clamp-3">{model.description}</p>
        )}
        <div className="mt-3 flex items-center gap-2">
          <span className={`px-2 py-1 rounded text-xs font-semibold uppercase
            ${model.format === 'glb' || model.format === 'gltf' ? 'bg-emerald-100 text-emerald-700' :
              model.format === 'obj' ? 'bg-blue-100 text-blue-700' :
              model.format === 'fbx' ? 'bg-purple-100 text-purple-700' :
              model.format === 'ply' || model.format === 'las' || model.format === 'laz' ? 'bg-amber-100 text-amber-700' :
              'bg-cyan-100 text-cyan-700'}`}
          >
            {model.format}
          </span>
          {model.metadata?.fileSize && (
            <span className="text-xs text-surface-400">{model.metadata.fileSize}</span>
          )}
        </div>
      </div>

      <div className="flex-1 overflow-y-auto">
        {/* Model Info */}
        <Section title="Model Information" icon={<Info size={16} />}>
          <div className="space-y-1">
            {model.metadata?.location && (
              <MetadataItem icon={<MapPin size={14} />} label="Location" value={model.metadata.location} />
            )}
            {model.metadata?.captureDate && (
              <MetadataItem 
                icon={<Calendar size={14} />} 
                label="Capture Date" 
                value={new Date(model.metadata.captureDate).toLocaleDateString('en-GB', { 
                  day: 'numeric', month: 'long', year: 'numeric' 
                })} 
              />
            )}
            {model.metadata?.droneModel && (
              <MetadataItem icon={<Navigation size={14} />} label="Drone" value={model.metadata.droneModel} />
            )}
            {model.metadata?.software && (
              <MetadataItem icon={<Cpu size={14} />} label="Software" value={model.metadata.software} />
            )}
            {model.metadata?.polygons && (
              <MetadataItem 
                icon={<FileBox size={14} />} 
                label="Polygons" 
                value={formatNumber(model.metadata.polygons)} 
              />
            )}
          </div>
        </Section>

        {/* Display Settings */}
        <Section title="Display Settings" icon={<Settings size={16} />}>
          <div className="space-y-4">
            {/* Ambient Light */}
            <div>
              <label className="flex items-center justify-between text-sm text-surface-600 mb-2">
                <span className="flex items-center gap-2">
                  <Sun size={14} />
                  Ambient Light
                </span>
                <span className="text-surface-400">{Math.round(settings.ambientIntensity * 100)}%</span>
              </label>
              <input
                type="range"
                min="0"
                max="1"
                step="0.1"
                value={settings.ambientIntensity}
                onChange={(e) => updateSettings({ ambientIntensity: parseFloat(e.target.value) })}
                className="w-full"
              />
            </div>

            {/* Point Size (for point clouds) */}
            {(model.format === 'ply' || model.format === 'las' || model.format === 'laz') && (
              <div>
                <label className="flex items-center justify-between text-sm text-surface-600 mb-2">
                  <span className="flex items-center gap-2">
                    <CircleDot size={14} />
                    Point Size
                  </span>
                  <span className="text-surface-400">{settings.pointSize}</span>
                </label>
                <input
                  type="range"
                  min="0.5"
                  max="5"
                  step="0.5"
                  value={settings.pointSize}
                  onChange={(e) => updateSettings({ pointSize: parseFloat(e.target.value) })}
                  className="w-full"
                />
              </div>
            )}

            {/* Background Color */}
            <div>
              <label className="flex items-center gap-2 text-sm text-surface-600 mb-2">
                <Palette size={14} />
                Background
              </label>
              <div className="flex gap-2">
                {['#f8fafc', '#ffffff', '#f1f5f9', '#e2e8f0', '#1e293b'].map(color => (
                  <button
                    key={color}
                    onClick={() => updateSettings({ backgroundColor: color })}
                    className={`w-8 h-8 rounded-lg border-2 transition-all ${
                      settings.backgroundColor === color 
                        ? 'border-primary-500 scale-110' 
                        : 'border-surface-200 hover:border-surface-300'
                    }`}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>

            {/* Toggle options */}
            <div className="space-y-2">
              <label className="flex items-center justify-between cursor-pointer">
                <span className="text-sm text-surface-600">Show Grid</span>
                <button
                  onClick={() => updateSettings({ showGrid: !settings.showGrid })}
                  className={`w-10 h-6 rounded-full transition-colors ${
                    settings.showGrid ? 'bg-primary-500' : 'bg-surface-200'
                  }`}
                >
                  <div className={`w-4 h-4 bg-white rounded-full shadow transition-transform mx-1 ${
                    settings.showGrid ? 'translate-x-4' : 'translate-x-0'
                  }`} />
                </button>
              </label>

              <label className="flex items-center justify-between cursor-pointer">
                <span className="text-sm text-surface-600">Show Axes</span>
                <button
                  onClick={() => updateSettings({ showAxes: !settings.showAxes })}
                  className={`w-10 h-6 rounded-full transition-colors ${
                    settings.showAxes ? 'bg-primary-500' : 'bg-surface-200'
                  }`}
                >
                  <div className={`w-4 h-4 bg-white rounded-full shadow transition-transform mx-1 ${
                    settings.showAxes ? 'translate-x-4' : 'translate-x-0'
                  }`} />
                </button>
              </label>

              <label className="flex items-center justify-between cursor-pointer">
                <span className="text-sm text-surface-600">Auto Rotate</span>
                <button
                  onClick={() => updateSettings({ autoRotate: !settings.autoRotate })}
                  className={`w-10 h-6 rounded-full transition-colors ${
                    settings.autoRotate ? 'bg-primary-500' : 'bg-surface-200'
                  }`}
                >
                  <div className={`w-4 h-4 bg-white rounded-full shadow transition-transform mx-1 ${
                    settings.autoRotate ? 'translate-x-4' : 'translate-x-0'
                  }`} />
                </button>
              </label>
            </div>
          </div>
        </Section>

        {/* Share */}
        <Section title="Share" icon={<Share2 size={16} />} defaultOpen={false}>
          <div className="space-y-3">
            <button
              onClick={handleCopyLink}
              className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-surface-100 hover:bg-surface-200 rounded-lg transition-colors text-sm font-medium"
            >
              {copied ? <Check size={16} className="text-green-500" /> : <Copy size={16} />}
              {copied ? 'Copied!' : 'Copy Link'}
            </button>
            
            <div className="flex gap-2">
              <button className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-surface-200 rounded-lg hover:bg-surface-50 transition-colors text-sm">
                <Link size={14} />
                Embed
              </button>
              <button className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-surface-200 rounded-lg hover:bg-surface-50 transition-colors text-sm">
                <Mail size={14} />
                Email
              </button>
            </div>
          </div>
        </Section>
      </div>

      {/* Footer */}
      <div className="p-4 border-t border-surface-100 text-center">
        <p className="text-xs text-surface-400">
          Powered by <span className="font-semibold gradient-text">Aerial Vision</span>
        </p>
      </div>
    </div>
  )
}

