"use client"

import { useState, useMemo } from "react"
import { motion, AnimatePresence } from "framer-motion"
import Link from "next/link"
import { 
  Search, Shield, Stethoscope, HardHat, UserPlus, 
  ArrowRight, Sparkles, ChevronRight
} from "lucide-react"
import naceKodlari from "@/data/nace-kodlari.json"

interface NaceKodu {
  kod: string
  tanim: string
  sinif: "Az Tehlikeli" | "Tehlikeli" | "Çok Tehlikeli"
}

const getSinifConfig = (sinif: string) => {
  switch (sinif) {
    case "Az Tehlikeli":
      return { color: "#10B981", bg: "bg-emerald-500", light: "bg-emerald-50", text: "text-emerald-600" }
    case "Tehlikeli":
      return { color: "#F59E0B", bg: "bg-amber-500", light: "bg-amber-50", text: "text-amber-600" }
    case "Çok Tehlikeli":
      return { color: "#EF4444", bg: "bg-red-500", light: "bg-red-50", text: "text-red-600" }
    default:
      return { color: "#64748B", bg: "bg-slate-500", light: "bg-slate-50", text: "text-slate-600" }
  }
}

const hesaplamaSecenekleri = [
  { baslik: "İşyeri Hekimi", icon: Stethoscope, href: "/calisma-sureleri/isyeri-hekimi", color: "#10B981" },
  { baslik: "İş Güvenliği Uzmanı", icon: HardHat, href: "/calisma-sureleri/is-guvenligi-uzmani", color: "#F59E0B" },
  { baslik: "Diğer Sağlık Personeli", icon: UserPlus, href: "/calisma-sureleri/diger-saglik-personeli", color: "#8B5CF6" },
]

export default function ISGHesaplamaRehberi() {
  const [arama, setArama] = useState("")
  const [sonuc, setSonuc] = useState<NaceKodu | null>(null)
  const [isFocused, setIsFocused] = useState(false)

  const aramaSonuclari = useMemo(() => {
    if (arama.length < 2) return []
    const aramaMetni = arama.toLowerCase().trim()
    
    // Önce kod ile ara
    let formattedKod = aramaMetni
    if (/^\d{6}$/.test(aramaMetni)) {
      formattedKod = `${aramaMetni.slice(0, 2)}.${aramaMetni.slice(2, 4)}.${aramaMetni.slice(4, 6)}`
    }
    
    const kodIleBulunan = (naceKodlari as NaceKodu[]).find(item => item.kod === formattedKod)
    if (kodIleBulunan) return [kodIleBulunan]
    
    // Tanım ile ara
    return (naceKodlari as NaceKodu[]).filter(item => 
      item.tanim.toLowerCase().includes(aramaMetni) || item.kod.includes(aramaMetni)
    ).slice(0, 6)
  }, [arama])

  const handleSelect = (item: NaceKodu) => {
    setSonuc(item)
    setArama("")
    setIsFocused(false)
  }

  const handleReset = () => {
    setSonuc(null)
    setArama("")
  }

  return (
    <section id="tehlike-sinifi" className="min-h-screen flex items-center bg-white overflow-visible scroll-mt-24">
      <div className="container mx-auto px-4 sm:px-6">
        <div className="max-w-3xl mx-auto">
          {/* Header */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            className="text-center mb-6"
          >
            <motion.div 
              className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#0F2A44]/5 border border-[#0F2A44]/10 mb-6"
              initial={{ opacity: 0, scale: 0.9 }}
              whileInView={{ opacity: 1, scale: 1 }}
              viewport={{ once: true }}
              transition={{ delay: 0.2 }}
            >
              <Sparkles className="w-4 h-4 text-[#F2B705]" />
              <span className="text-[#0F2A44] text-sm font-medium">Hızlı Hesaplama</span>
            </motion.div>
            
            <h2 className="text-2xl sm:text-4xl lg:text-5xl font-bold text-[#0F2A44] mb-4">
              İSG İhtiyacınızı{" "}
              <span className="text-[#C8102E]">Hesaplayın</span>
            </h2>
            <p className="text-[#2E2E2E]/60">
              NACE kodunuzu veya faaliyet alanınızı girin
            </p>
          </motion.div>

          {/* Search Box */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ delay: 0.3 }}
          >
            <AnimatePresence mode="wait">
              {!sonuc ? (
                <motion.div
                  key="search"
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  className="relative z-20"
                >
                  {/* Search Input */}
                  <div className={`relative bg-white rounded-2xl shadow-xl border border-[#0F2A44]/10 transition-all duration-300 ${
                    isFocused ? "ring-4 ring-[#0F2A44]/10 border-[#0F2A44]/20" : ""
                  }`}>
                    <div className="flex items-center px-6 py-5">
                      <Search className="w-6 h-6 text-[#0F2A44]/40 mr-4" />
                      <input
                        type="text"
                        value={arama}
                        onChange={(e) => setArama(e.target.value)}
                        onFocus={() => setIsFocused(true)}
                        onBlur={() => setTimeout(() => setIsFocused(false), 200)}
                        placeholder="NACE kodu veya faaliyet alanı yazın..."
                        className="flex-1 text-lg text-[#0F2A44] placeholder:text-[#0F2A44]/40 bg-transparent outline-none"
                      />
                      {arama && (
                        <motion.button
                          initial={{ opacity: 0, scale: 0.8 }}
                          animate={{ opacity: 1, scale: 1 }}
                          onClick={() => setArama("")}
                          className="text-[#0F2A44]/40 hover:text-[#0F2A44] transition-colors p-1"
                        >
                          ✕
                        </motion.button>
                      )}
                    </div>

                    {/* Search Results Dropdown */}
                    <AnimatePresence>
                      {aramaSonuclari.length > 0 && isFocused && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: "auto" }}
                          exit={{ opacity: 0, height: 0 }}
                          className="border-t border-[#0F2A44]/10 overflow-hidden"
                        >
                          <div className="max-h-80 overflow-y-auto">
                            {aramaSonuclari.map((item, index) => {
                              const config = getSinifConfig(item.sinif)
                              return (
                                <motion.button
                                  key={item.kod}
                                  initial={{ opacity: 0, x: -10 }}
                                  animate={{ opacity: 1, x: 0 }}
                                  transition={{ delay: index * 0.05 }}
                                  onClick={() => handleSelect(item)}
                                  className="w-full flex items-center gap-4 px-6 py-4 hover:bg-[#F5F7FA] transition-colors text-left border-b border-[#0F2A44]/5 last:border-b-0"
                                >
                                  <div className={`w-3 h-3 rounded-full flex-shrink-0 ${config.bg}`} />
                                  <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-2 mb-1">
                                      <span className="font-mono text-sm text-[#0F2A44]/60">{item.kod}</span>
                                      <span className={`text-xs px-2 py-0.5 rounded-full ${config.light} ${config.text} font-medium`}>
                                        {item.sinif}
                                      </span>
                                    </div>
                                    <p className="text-[#0F2A44] text-sm line-clamp-2">{item.tanim}</p>
                                  </div>
                                  <ChevronRight className="w-5 h-5 text-[#0F2A44]/30 flex-shrink-0" />
                                </motion.button>
                              )
                            })}
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>

                  {/* Hint */}
                  <motion.p
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: 0.5 }}
                    className="text-center text-[#2E2E2E]/40 text-sm mt-4"
                  >
                    Örn: 10.89.05 veya &quot;inşaat&quot;, &quot;tekstil&quot;, &quot;gıda&quot;
                  </motion.p>

                  {/* Tehlike Sınıfları Bilgi */}
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.6 }}
                    className="mt-10"
                  >
                    <h3 className="text-center text-[#0F2A44] font-semibold mb-4">Tehlike Sınıfları</h3>
                    <div className="grid sm:grid-cols-3 gap-3">
                      <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-4">
                        <div className="flex items-center gap-2 mb-2">
                          <div className="w-3 h-3 rounded-full bg-emerald-500" />
                          <span className="font-semibold text-emerald-700 text-sm">Az Tehlikeli</span>
                        </div>
                        <p className="text-emerald-600/80 text-xs">Büro işleri, ofisler, bankalar gibi düşük riskli işyerleri</p>
                      </div>
                      <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
                        <div className="flex items-center gap-2 mb-2">
                          <div className="w-3 h-3 rounded-full bg-amber-500" />
                          <span className="font-semibold text-amber-700 text-sm">Tehlikeli</span>
                        </div>
                        <p className="text-amber-600/80 text-xs">Gıda üretimi, tekstil, makine kullanılan orta riskli işyerleri</p>
                      </div>
                      <div className="bg-red-50 border border-red-200 rounded-xl p-4">
                        <div className="flex items-center gap-2 mb-2">
                          <div className="w-3 h-3 rounded-full bg-red-500" />
                          <span className="font-semibold text-red-700 text-sm">Çok Tehlikeli</span>
                        </div>
                        <p className="text-red-600/80 text-xs">Maden, inşaat, kimya gibi yüksek kaza riskli işyerleri</p>
                      </div>
                    </div>
                    <p className="text-center text-[#2E2E2E]/50 text-xs mt-4">
                      Tehlike sınıfınız, işyeri hekimi ve iş güvenliği uzmanı çalıştırma sürenizi belirler.
                    </p>
                  </motion.div>
                </motion.div>
              ) : (
                <motion.div
                  key="result"
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  className="space-y-6"
                >
                  {/* Result Card */}
                  {(() => {
                    const config = getSinifConfig(sonuc.sinif)
                    return (
                      <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="bg-white rounded-2xl p-4 sm:p-6 shadow-xl border border-[#0F2A44]/10"
                      >
                        <div className="flex items-start gap-3 sm:gap-4">
                          <motion.div
                            initial={{ scale: 0 }}
                            animate={{ scale: 1 }}
                            transition={{ type: "spring", delay: 0.2 }}
                            className={`w-12 h-12 sm:w-14 sm:h-14 ${config.bg} rounded-xl flex items-center justify-center shadow-lg flex-shrink-0`}
                            style={{ boxShadow: `0 10px 30px ${config.color}40` }}
                          >
                            <Shield className="w-6 h-6 sm:w-7 sm:h-7 text-white" />
                          </motion.div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 sm:gap-3 mb-2 flex-wrap">
                              <span className="font-mono text-base sm:text-lg font-bold text-[#0F2A44]">{sonuc.kod}</span>
                              <span className={`px-2 sm:px-3 py-0.5 sm:py-1 rounded-full text-xs sm:text-sm font-medium ${config.bg} text-white`}>
                                {sonuc.sinif}
                              </span>
                            </div>
                            <p className="text-[#0F2A44]/70 text-xs sm:text-sm leading-relaxed">{sonuc.tanim}</p>
                          </div>
                          <button
                            onClick={handleReset}
                            className="text-[#0F2A44]/40 hover:text-[#0F2A44] transition-colors p-1 sm:p-2 flex-shrink-0"
                          >
                            ✕
                          </button>
                        </div>
                      </motion.div>
                    )
                  })()}

                  {/* Action Cards */}
                  <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: 0.3 }}
                    className="grid grid-cols-1 gap-3 sm:gap-4"
                  >
                    {hesaplamaSecenekleri.map((secenek, index) => {
                      const Icon = secenek.icon
                      return (
                        <motion.div
                          key={secenek.baslik}
                          initial={{ opacity: 0, y: 20 }}
                          animate={{ opacity: 1, y: 0 }}
                          transition={{ delay: 0.4 + index * 0.1 }}
                        >
                          <Link href={`${secenek.href}?sinif=${encodeURIComponent(sonuc.sinif)}`}>
                            <motion.div
                              whileHover={{ scale: 1.02, y: -4 }}
                              whileTap={{ scale: 0.98 }}
                              className="bg-white border border-[#0F2A44]/10 rounded-xl p-4 sm:p-5 hover:shadow-lg hover:border-[#0F2A44]/20 transition-all cursor-pointer group h-full"
                            >
                              <div 
                                className="w-10 h-10 sm:w-12 sm:h-12 rounded-lg flex items-center justify-center mb-2 sm:mb-3"
                                style={{ backgroundColor: `${secenek.color}15` }}
                              >
                                <Icon className="w-5 h-5 sm:w-6 sm:h-6" style={{ color: secenek.color }} />
                              </div>
                              <h3 className="text-[#0F2A44] font-semibold text-sm sm:text-base mb-1">{secenek.baslik}</h3>
                              <div className="flex items-center gap-1 text-[#0F2A44]/50 text-xs sm:text-sm group-hover:text-[#0F2A44] transition-colors">
                                <span>Hesapla</span>
                                <ArrowRight className="w-3 h-3 sm:w-4 sm:h-4 group-hover:translate-x-1 transition-transform" />
                              </div>
                            </motion.div>
                          </Link>
                        </motion.div>
                      )
                    })}
                  </motion.div>

                  {/* CTA */}
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.7 }}
                  >
                    <Link href="#basvuru">
                      <motion.div
                        whileHover={{ scale: 1.01 }}
                        whileTap={{ scale: 0.99 }}
                        className="bg-[#F2B705] rounded-xl p-4 sm:p-5 flex items-center justify-between cursor-pointer group shadow-lg shadow-[#F2B705]/20"
                      >
                        <div>
                          <h3 className="text-[#0F2A44] font-semibold text-base sm:text-lg">Hemen Teklif Alın</h3>
                          <p className="text-[#0F2A44]/70 text-xs sm:text-sm">Size özel fiyat teklifi hazırlayalım</p>
                        </div>
                        <ArrowRight className="w-5 h-5 sm:w-6 sm:h-6 text-[#0F2A44] group-hover:translate-x-2 transition-transform flex-shrink-0" />
                      </motion.div>
                    </Link>
                  </motion.div>
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        </div>
      </div>
    </section>
  )
}
