'use client'

import { Suspense, useState, useRef } from 'react'
import { Canvas } from '@react-three/fiber'
import { OrbitControls, Environment, ContactShadows, Box, Plane } from '@react-three/drei'
import * as THREE from 'three'
import { Loader2, Palette, Grid3X3, Lightbulb, Sofa, Box as BoxIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'

interface RoomConfig {
  wallColor: string
  floorType: 'wood' | 'tile' | 'marble'
  lighting: 'natural' | 'warm' | 'cool'
  furniture: boolean
}

function Floor({ type }: { type: string }) {
  const colors = { wood: '#8B4513', tile: '#E0E0E0', marble: '#F5F5F5' }
  return (
    <Plane args={[10, 10]} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0, 0]}>
      <meshStandardMaterial color={colors[type as keyof typeof colors]} roughness={type === 'marble' ? 0.1 : 0.8} />
    </Plane>
  )
}

function Walls({ color }: { color: string }) {
  return (
    <group>
      <Box args={[10, 3, 0.2]} position={[0, 1.5, -5]}>
        <meshStandardMaterial color={color} />
      </Box>
      <Box args={[0.2, 3, 10]} position={[-5, 1.5, 0]}>
        <meshStandardMaterial color={color} />
      </Box>
      <Box args={[0.2, 3, 10]} position={[5, 1.5, 0]}>
        <meshStandardMaterial color={color} />
      </Box>
    </group>
  )
}

function Furniture() {
  return (
    <group>
      <Box args={[2, 0.5, 1]} position={[0, 0.25, 0]}>
        <meshStandardMaterial color="#4A5568" />
      </Box>
      <Box args={[0.5, 1, 0.5]} position={[-1.5, 0.5, -1.5]}>
        <meshStandardMaterial color="#2D3748" />
      </Box>
    </group>
  )
}

function Room({ config }: { config: RoomConfig }) {
  const lightColors = { natural: '#ffffff', warm: '#ffaa77', cool: '#aaccff' }
  
  return (
    <>
      <ambientLight intensity={0.5} />
      <directionalLight position={[5, 5, 5]} intensity={1} color={lightColors[config.lighting]} />
      <Floor type={config.floorType} />
      <Walls color={config.wallColor} />
      {config.furniture && <Furniture />}
      <ContactShadows position={[0, 0.01, 0]} opacity={0.4} scale={20} blur={2} />
      <Environment preset="apartment" />
    </>
  )
}

export function Property3DViewer() {
  const [config, setConfig] = useState<RoomConfig>({
    wallColor: '#F5F5DC',
    floorType: 'wood',
    lighting: 'natural',
    furniture: true
  })

  const colors = ['#FFFFFF', '#F5F5DC', '#E8E8E8', '#D4C4B0', '#B0C4DE', '#90EE90']

  return (
    <div className="bg-white rounded-2xl shadow-xl overflow-hidden">
      <div className="p-4 border-b flex justify-between items-center">
        <div>
          <h3 className="text-xl font-bold flex items-center gap-2">
            <BoxIcon className="w-6 h-6 text-purple-600" />
            استوديو التصميم 3D
          </h3>
          <p className="text-sm text-gray-600">صمم منزلك قبل الشراء</p>
        </div>
      </div>

      <div className="h-[400px] relative">
        <Canvas shadows camera={{ position: [8, 5, 8], fov: 50 }}>
          <Suspense fallback={null}>
            <Room config={config} />
          </Suspense>
          <OrbitControls enablePan={true} enableZoom={true} maxPolarAngle={Math.PI / 2} />
        </Canvas>
      </div>

      <div className="p-4 bg-gray-50 border-t">
        <div className="grid grid-cols-4 gap-4">
          <div>
            <label className="text-xs font-bold text-gray-600 mb-2 block flex items-center gap-1">
              <Palette className="w-3 h-3" /> الجدران
            </label>
            <div className="flex gap-1 flex-wrap">
              {colors.map(c => (
                <button
                  key={c}
                  onClick={() => setConfig({...config, wallColor: c})}
                  className={`w-6 h-6 rounded-full border-2 ${config.wallColor === c ? 'border-blue-600' : 'border-gray-300'}`}
                  style={{ backgroundColor: c }}
                />
              ))}
            </div>
          </div>

          <div>
            <label className="text-xs font-bold text-gray-600 mb-2 block flex items-center gap-1">
              <Grid3X3 className="w-3 h-3" /> الأرضية
            </label>
            <select 
              value={config.floorType}
              onChange={(e) => setConfig({...config, floorType: e.target.value as any})}
              className="w-full text-sm p-1.5 rounded border"
            >
              <option value="wood">باركيه</option>
              <option value="tile">سيراميك</option>
              <option value="marble">رخام</option>
            </select>
          </div>

          <div>
            <label className="text-xs font-bold text-gray-600 mb-2 block flex items-center gap-1">
              <Lightbulb className="w-3 h-3" /> الإضاءة
            </label>
            <select 
              value={config.lighting}
              onChange={(e) => setConfig({...config, lighting: e.target.value as any})}
              className="w-full text-sm p-1.5 rounded border"
            >
              <option value="natural">طبيعية</option>
              <option value="warm">دافئة</option>
              <option value="cool">باردة</option>
            </select>
          </div>

          <div>
            <label className="text-xs font-bold text-gray-600 mb-2 block flex items-center gap-1">
              <Sofa className="w-3 h-3" /> الأثاث
            </label>
            <Button 
              variant={config.furniture ? 'default' : 'outline'} 
              size="sm"
              onClick={() => setConfig({...config, furniture: !config.furniture})}
              className="w-full text-xs"
            >
              {config.furniture ? 'إخفاء' : 'إظهار'}
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
