"use client"

import React from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Card, CardContent, CardHeader, CardTitle } from '../../ui/card'
import { Button } from '../../ui/button'
import { cn } from '../../../lib/utils'
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  AreaChart,
  Area,
  PieChart,
  Pie,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  Cell
} from 'recharts'
import {
  MoreVertical,
  Download,
  Maximize2,
  RefreshCw,
  Palette,
  Settings,
  Filter
} from 'lucide-react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
} from '../../ui/dropdown-menu'
import { ChartData } from '../types'

interface ChartWidgetProps {
  id: string
  title: string
  description?: string
  data: ChartData
  className?: string
  height?: number
  onAction?: (action: string, data?: any) => void
  loading?: boolean
  refreshing?: boolean
  glassmorphism?: boolean
  interactive?: boolean
}

// Renk paleti
const CHART_COLORS = {
  default: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899'],
  pastel: ['#93c5fd', '#86efac', '#fcd34d', '#fca5a5', '#c4b5fd', '#fbcfe8'],
  vibrant: ['#2563eb', '#059669', '#d97706', '#dc2626', '#7c3aed', '#db2777'],
  monochrome: ['#1f2937', '#374151', '#4b5563', '#6b7280', '#9ca3af', '#d1d5db']
}

export function ChartWidget({
  id,
  title,
  description,
  data,
  className,
  height = 300,
  onAction,
  loading = false,
  refreshing = false,
  glassmorphism = false,
  interactive = true
}: ChartWidgetProps) {
  const [colorScheme, setColorScheme] = React.useState<keyof typeof CHART_COLORS>('default')
  const [isFullscreen, setIsFullscreen] = React.useState(false)
  
  const colors = CHART_COLORS[colorScheme]

  // Custom tooltip
  const CustomTooltip = ({ active, payload, label }: any) => {
    if (!active || !payload) return null

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.9 }}
        animate={{ opacity: 1, scale: 1 }}
        className={cn(
          "p-3 rounded-lg shadow-lg",
          glassmorphism 
            ? "bg-background/80 backdrop-blur-md border border-white/10" 
            : "bg-background border"
        )}
      >
        <p className="text-sm font-medium">{label}</p>
        {payload.map((entry: any, index: number) => (
          <p key={index} className="text-sm mt-1">
            <span 
              className="inline-block w-3 h-3 rounded-full mr-2"
              style={{ backgroundColor: entry.color }}
            />
            {entry.name}: {entry.value}
          </p>
        ))}
      </motion.div>
    )
  }

  // Chart renderer
  const renderChart = () => {
    if (!data.data || data.data.length === 0) {
      return (
        <div className="flex items-center justify-center h-full text-muted-foreground">
          No data available
        </div>
      )
    }

    const chartProps = {
      data: data.data,
      margin: { top: 5, right: 30, left: 20, bottom: 5 }
    }

    switch (data.type) {
      case 'line':
        return (
          <ResponsiveContainer width="100%" height={height}>
            <LineChart {...chartProps}>
              <CartesianGrid strokeDasharray="3 3" className="opacity-30" />
              <XAxis dataKey="name" />
              <YAxis />
              <Tooltip content={<CustomTooltip />} />
              {interactive && <Legend />}
              {Object.keys(data.data[0])
                .filter(key => key !== 'name')
                .map((key, index) => (
                  <Line
                    key={key}
                    type="monotone"
                    dataKey={key}
                    stroke={colors[index % colors.length]}
                    strokeWidth={2}
                    dot={{ r: 4 }}
                    activeDot={{ r: 6 }}
                  />
                ))}
            </LineChart>
          </ResponsiveContainer>
        )

      case 'bar':
        return (
          <ResponsiveContainer width="100%" height={height}>
            <BarChart {...chartProps}>
              <CartesianGrid strokeDasharray="3 3" className="opacity-30" />
              <XAxis dataKey="name" />
              <YAxis />
              <Tooltip content={<CustomTooltip />} />
              {interactive && <Legend />}
              {Object.keys(data.data[0])
                .filter(key => key !== 'name')
                .map((key, index) => (
                  <Bar
                    key={key}
                    dataKey={key}
                    fill={colors[index % colors.length]}
                    radius={[4, 4, 0, 0]}
                  />
                ))}
            </BarChart>
          </ResponsiveContainer>
        )

      case 'area':
        return (
          <ResponsiveContainer width="100%" height={height}>
            <AreaChart {...chartProps}>
              <CartesianGrid strokeDasharray="3 3" className="opacity-30" />
              <XAxis dataKey="name" />
              <YAxis />
              <Tooltip content={<CustomTooltip />} />
              {interactive && <Legend />}
              {Object.keys(data.data[0])
                .filter(key => key !== 'name')
                .map((key, index) => (
                  <Area
                    key={key}
                    type="monotone"
                    dataKey={key}
                    stroke={colors[index % colors.length]}
                    fill={colors[index % colors.length]}
                    fillOpacity={0.2}
                  />
                ))}
            </AreaChart>
          </ResponsiveContainer>
        )

      case 'pie':
      case 'donut':
        return (
          <ResponsiveContainer width="100%" height={height}>
            <PieChart>
              <Pie
                data={data.data}
                cx="50%"
                cy="50%"
                labelLine={false}
                label={interactive}
                outerRadius={data.type === 'donut' ? 80 : 100}
                innerRadius={data.type === 'donut' ? 50 : 0}
                fill="#8884d8"
                dataKey="value"
              >
                {data.data.map((entry: any, index: number) => (
                  <Cell key={`cell-${index}`} fill={colors[index % colors.length]} />
                ))}
              </Pie>
              <Tooltip content={<CustomTooltip />} />
              {interactive && <Legend />}
            </PieChart>
          </ResponsiveContainer>
        )

      case 'radar':
        return (
          <ResponsiveContainer width="100%" height={height}>
            <RadarChart data={data.data}>
              <PolarGrid />
              <PolarAngleAxis dataKey="subject" />
              <PolarRadiusAxis />
              {Object.keys(data.data[0])
                .filter(key => key !== 'subject')
                .map((key, index) => (
                  <Radar
                    key={key}
                    name={key}
                    dataKey={key}
                    stroke={colors[index % colors.length]}
                    fill={colors[index % colors.length]}
                    fillOpacity={0.3}
                  />
                ))}
              <Tooltip content={<CustomTooltip />} />
              {interactive && <Legend />}
            </RadarChart>
          </ResponsiveContainer>
        )

      default:
        return null
    }
  }

  // Card variants
  const cardVariants = {
    initial: { opacity: 0, scale: 0.95 },
    animate: { 
      opacity: 1, 
      scale: 1,
      transition: { duration: 0.3, ease: "easeOut" }
    }
  }

  return (
    <motion.div
      variants={cardVariants}
      initial="initial"
      animate="animate"
      className={cn(isFullscreen && "fixed inset-4 z-50")}
    >
      <Card className={cn(
        "relative overflow-hidden transition-all duration-300",
        glassmorphism && "bg-background/60 backdrop-blur-md border-white/10",
        isFullscreen && "h-full",
        className
      )}>
        {/* Header */}
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <div>
            <CardTitle className="text-base font-semibold">{title}</CardTitle>
            {description && (
              <p className="text-sm text-muted-foreground mt-1">{description}</p>
            )}
          </div>

          {/* Actions */}
          <div className="flex items-center gap-2">
            {refreshing && (
              <motion.div
                animate={{ rotate: 360 }}
                transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
              >
                <RefreshCw className="h-4 w-4 text-muted-foreground" />
              </motion.div>
            )}

            {interactive && (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                    <MoreVertical className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-48">
                  <DropdownMenuItem onClick={() => {
                    setIsFullscreen(!isFullscreen)
                    onAction?.('fullscreen', { fullscreen: !isFullscreen })
                  }}>
                    <Maximize2 className="mr-2 h-4 w-4" />
                    {isFullscreen ? 'Exit Fullscreen' : 'Fullscreen'}
                  </DropdownMenuItem>
                  
                  <DropdownMenuSub>
                    <DropdownMenuSubTrigger>
                      <Palette className="mr-2 h-4 w-4" />
                      Color Scheme
                    </DropdownMenuSubTrigger>
                    <DropdownMenuSubContent>
                      {Object.keys(CHART_COLORS).map((scheme) => (
                        <DropdownMenuItem
                          key={scheme}
                          onClick={() => setColorScheme(scheme as keyof typeof CHART_COLORS)}
                        >
                          <div className="flex items-center gap-2">
                            <div className="flex gap-1">
                              {CHART_COLORS[scheme as keyof typeof CHART_COLORS].slice(0, 3).map((color, i) => (
                                <div
                                  key={i}
                                  className="w-3 h-3 rounded-full"
                                  style={{ backgroundColor: color }}
                                />
                              ))}
                            </div>
                            <span className="capitalize">{scheme}</span>
                          </div>
                        </DropdownMenuItem>
                      ))}
                    </DropdownMenuSubContent>
                  </DropdownMenuSub>

                  <DropdownMenuSeparator />
                  
                  <DropdownMenuItem onClick={() => onAction?.('export', { format: 'png' })}>
                    <Download className="mr-2 h-4 w-4" />
                    Export as PNG
                  </DropdownMenuItem>
                  
                  <DropdownMenuItem onClick={() => onAction?.('export', { format: 'csv' })}>
                    <Download className="mr-2 h-4 w-4" />
                    Export Data
                  </DropdownMenuItem>
                  
                  <DropdownMenuSeparator />
                  
                  <DropdownMenuItem onClick={() => onAction?.('filter')}>
                    <Filter className="mr-2 h-4 w-4" />
                    Filter Data
                  </DropdownMenuItem>
                  
                  <DropdownMenuItem onClick={() => onAction?.('settings')}>
                    <Settings className="mr-2 h-4 w-4" />
                    Chart Settings
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            )}
          </div>
        </CardHeader>

        {/* Chart Content */}
        <CardContent className="p-0 px-4 pb-4">
          <AnimatePresence mode="wait">
            {loading ? (
              <motion.div
                key="loading"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="flex items-center justify-center"
                style={{ height }}
              >
                <div className="space-y-2">
                  <div className="animate-pulse bg-muted h-4 w-32 rounded" />
                  <div className="animate-pulse bg-muted h-4 w-24 rounded" />
                  <div className="animate-pulse bg-muted h-4 w-28 rounded" />
                </div>
              </motion.div>
            ) : (
              <motion.div
                key="chart"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                transition={{ duration: 0.3 }}
              >
                {renderChart()}
              </motion.div>
            )}
          </AnimatePresence>
        </CardContent>
      </Card>
    </motion.div>
  )
}

export default ChartWidget