'use client';

import { useState, useEffect, useMemo } from 'react';
import { useSession, signOut } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import {
  Gauge, Calculator, Database, Wrench, Monitor, LogOut, Plus,
  AlertTriangle, CheckCircle, Info, ChevronDown
} from 'lucide-react';
import { calculateSpeedsAndFeeds, CalculationResult } from '@/lib/calculations';

interface Material {
  id: string;
  name: string;
  category: string;
  sfm: number;
  chipLoad: number;
}

interface Tool {
  id: string;
  name: string;
  type: string;
  diameter: number;
  flutes: number;
  coating?: string;
}

interface Machine {
  id: string;
  name: string;
  maxRpm: number;
  maxFeedRate: number;
  horsepower: number;
  controller?: string;
}

export default function DashboardClient() {
  const router = useRouter();
  const { data: session, status } = useSession() || {};
  const [materials, setMaterials] = useState<Material[]>([]);
  const [tools, setTools] = useState<Tool[]>([]);
  const [machines, setMachines] = useState<Machine[]>([]);
  const [selectedMaterial, setSelectedMaterial] = useState<Material | null>(null);
  const [selectedTool, setSelectedTool] = useState<Tool | null>(null);
  const [selectedMachine, setSelectedMachine] = useState<Machine | null>(null);
  const [cutDepth, setCutDepth] = useState(0.125);
  const [cutWidth, setCutWidth] = useState(0.25);
  const [aggressiveness, setAggressiveness] = useState(50);
  const [result, setResult] = useState<CalculationResult | null>(null);
  const [activeTab, setActiveTab] = useState<'calculator' | 'materials' | 'tools' | 'machines'>('calculator');

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.replace('/login');
    }
  }, [status, router]);

  useEffect(() => {
    Promise.all([
      fetch('/api/materials').then(r => r.json()),
      fetch('/api/tools').then(r => r.json()),
      fetch('/api/machines').then(r => r.json()),
    ]).then(([mats, tls, mchs]) => {
      setMaterials(Array.isArray(mats) ? mats : []);
      setTools(Array.isArray(tls) ? tls : []);
      setMachines(Array.isArray(mchs) ? mchs : []);
    }).catch(console.error);
  }, []);

  useEffect(() => {
    if (selectedMaterial && selectedTool && selectedMachine) {
      const res = calculateSpeedsAndFeeds({
        materialSfm: selectedMaterial.sfm,
        materialChipLoad: selectedMaterial.chipLoad,
        toolDiameter: selectedTool.diameter,
        toolFlutes: selectedTool.flutes,
        machineMaxRpm: selectedMachine.maxRpm,
        machineMaxFeedRate: selectedMachine.maxFeedRate,
        machineHorsepower: selectedMachine.horsepower,
        cutDepth,
        cutWidth,
        aggressiveness,
      });
      setResult(res);
    }
  }, [selectedMaterial, selectedTool, selectedMachine, cutDepth, cutWidth, aggressiveness]);

  const getAggressivenessLabel = () => {
    if (aggressiveness < 30) return 'Conservative (Finishing)';
    if (aggressiveness < 70) return 'Balanced';
    return 'Aggressive (Roughing)';
  };

  const groupedMaterials = (materials ?? []).reduce<Record<string, Material[]>>((acc, mat) => {
    const cat = mat?.category ?? 'Other';
    if (!acc[cat]) acc[cat] = [];
    acc[cat].push(mat);
    return acc;
  }, {});

  const groupedTools = (tools ?? []).reduce<Record<string, Tool[]>>((acc, tool) => {
    const type = tool?.type ?? 'Other';
    if (!acc[type]) acc[type] = [];
    acc[type].push(tool);
    return acc;
  }, {});

  if (status === 'loading') {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="text-center">
          <Gauge className="w-12 h-12 text-primary animate-pulse mx-auto mb-4" />
          <p className="text-muted-foreground">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-background to-secondary/20">
      <header className="sticky top-0 z-50 backdrop-blur-md bg-background/80 border-b border-border">
        <div className="max-w-7xl mx-auto px-4 py-3 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Gauge className="w-8 h-8 text-primary" />
            <span className="font-bold text-xl">CNC Calculator</span>
          </div>
          <div className="flex items-center gap-4">
            <span className="text-sm text-muted-foreground">
              {session?.user?.name || session?.user?.email || 'User'}
            </span>
            <button
              onClick={() => signOut({ callbackUrl: '/' })}
              className="p-2 hover:bg-secondary rounded-lg transition-colors"
            >
              <LogOut className="w-5 h-5" />
            </button>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 py-6">
        <div className="flex gap-2 mb-6 overflow-x-auto pb-2">
          {[
            { id: 'calculator' as const, icon: Calculator, label: 'Calculator' },
            { id: 'materials' as const, icon: Database, label: 'Materials' },
            { id: 'tools' as const, icon: Wrench, label: 'Tools' },
            { id: 'machines' as const, icon: Monitor, label: 'Machines' },
          ].map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-colors whitespace-nowrap ${
                activeTab === tab.id
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-card hover:bg-secondary'
              }`}
            >
              <tab.icon className="w-5 h-5" />
              {tab.label}
            </button>
          ))}
        </div>

        {activeTab === 'calculator' && (
          <div className="grid lg:grid-cols-2 gap-6">
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              className="bg-card rounded-xl p-6 shadow-lg"
            >
              <h2 className="text-xl font-bold mb-6 flex items-center gap-2">
                <Calculator className="w-6 h-6 text-primary" />
                Input Parameters
              </h2>

              <div className="space-y-5">
                <div>
                  <label className="block text-sm font-medium mb-2">Material</label>
                  <div className="relative">
                    <select
                      value={selectedMaterial?.id ?? ''}
                      onChange={(e) => setSelectedMaterial(materials?.find(m => m?.id === e.target.value) ?? null)}
                      className="w-full p-3 bg-secondary rounded-lg appearance-none cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                      <option value="">Select material...</option>
                      {Object.entries(groupedMaterials ?? {}).map(([category, mats]) => (
                        <optgroup key={category} label={category}>
                          {(mats ?? []).map(mat => (
                            <option key={mat?.id} value={mat?.id}>{mat?.name}</option>
                          ))}
                        </optgroup>
                      ))}
                    </select>
                    <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground pointer-events-none" />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2">Tool</label>
                  <div className="relative">
                    <select
                      value={selectedTool?.id ?? ''}
                      onChange={(e) => setSelectedTool(tools?.find(t => t?.id === e.target.value) ?? null)}
                      className="w-full p-3 bg-secondary rounded-lg appearance-none cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                      <option value="">Select tool...</option>
                      {Object.entries(groupedTools ?? {}).map(([type, tls]) => (
                        <optgroup key={type} label={type}>
                          {(tls ?? []).map(tool => (
                            <option key={tool?.id} value={tool?.id}>{tool?.name}</option>
                          ))}
                        </optgroup>
                      ))}
                    </select>
                    <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground pointer-events-none" />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2">Machine</label>
                  <div className="relative">
                    <select
                      value={selectedMachine?.id ?? ''}
                      onChange={(e) => setSelectedMachine(machines?.find(m => m?.id === e.target.value) ?? null)}
                      className="w-full p-3 bg-secondary rounded-lg appearance-none cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                      <option value="">Select machine...</option>
                      {(machines ?? []).map(machine => (
                        <option key={machine?.id} value={machine?.id}>
                          {machine?.name} {machine?.controller ? `(${machine.controller})` : ''}
                        </option>
                      ))}
                    </select>
                    <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground pointer-events-none" />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium mb-2">Cut Depth (in)</label>
                    <input
                      type="number"
                      value={cutDepth}
                      onChange={(e) => setCutDepth(parseFloat(e.target.value) || 0)}
                      step="0.0625"
                      min="0.001"
                      className="w-full p-3 bg-secondary rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-2">Cut Width (in)</label>
                    <input
                      type="number"
                      value={cutWidth}
                      onChange={(e) => setCutWidth(parseFloat(e.target.value) || 0)}
                      step="0.0625"
                      min="0.001"
                      className="w-full p-3 bg-secondary rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                    />
                  </div>
                </div>

                <div>
                  <div className="flex justify-between mb-2">
                    <label className="text-sm font-medium">Aggressiveness</label>
                    <span className="text-sm text-primary">{getAggressivenessLabel()}</span>
                  </div>
                  <div className="relative">
                    <input
                      type="range"
                      min="0"
                      max="100"
                      value={aggressiveness}
                      onChange={(e) => setAggressiveness(parseInt(e.target.value))}
                      className="w-full h-2 bg-secondary rounded-lg appearance-none cursor-pointer accent-primary"
                    />
                    <div className="flex justify-between text-xs text-muted-foreground mt-1">
                      <span>🐢 Conservative</span>
                      <span>Aggressive 🐇</span>
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              className="bg-card rounded-xl p-6 shadow-lg"
            >
              <h2 className="text-xl font-bold mb-6 flex items-center gap-2">
                <Gauge className="w-6 h-6 text-primary" />
                Calculated Results
              </h2>

              {result ? (
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <ResultCard
                      label="Spindle Speed"
                      value={result.rpm}
                      unit="RPM"
                      warning={result.rpmLimited}
                    />
                    <ResultCard
                      label="Feed Rate"
                      value={result.feedRate}
                      unit="IPM"
                      warning={result.feedLimited}
                    />
                    <ResultCard
                      label="Chip Load"
                      value={result.chipLoad}
                      unit="in/tooth"
                    />
                    <ResultCard
                      label="MRR"
                      value={result.mrr}
                      unit="in³/min"
                      warning={result.powerWarning}
                    />
                    <ResultCard
                      label="Surface Speed"
                      value={result.sfpm}
                      unit="SFPM"
                      className="col-span-2"
                    />
                  </div>

                  {(result?.recommendations?.length ?? 0) > 0 && (
                    <div className="mt-4 space-y-2">
                      <h3 className="text-sm font-medium flex items-center gap-2">
                        <Info className="w-4 h-4 text-primary" />
                        Recommendations
                      </h3>
                      {(result?.recommendations ?? []).map((rec, i) => (
                        <div
                          key={i}
                          className="flex items-start gap-2 text-sm text-muted-foreground bg-secondary/50 p-2 rounded-lg"
                        >
                          {rec?.includes('limited') || rec?.includes('High') ? (
                            <AlertTriangle className="w-4 h-4 text-yellow-500 mt-0.5 flex-shrink-0" />
                          ) : (
                            <CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
                          )}
                          {rec}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ) : (
                <div className="text-center text-muted-foreground py-12">
                  <Calculator className="w-12 h-12 mx-auto mb-4 opacity-50" />
                  <p>Select material, tool, and machine to calculate</p>
                </div>
              )}
            </motion.div>
          </div>
        )}

        {activeTab === 'materials' && (
          <DatabaseView
            title="Materials Database"
            icon={Database}
            items={materials}
            groupBy="category"
            columns={['name', 'category', 'sfm', 'chipLoad']}
            columnLabels={{ name: 'Name', category: 'Category', sfm: 'SFM', chipLoad: 'Chip Load' }}
          />
        )}

        {activeTab === 'tools' && (
          <DatabaseView
            title="Tools Database"
            icon={Wrench}
            items={tools}
            groupBy="type"
            columns={['name', 'type', 'diameter', 'flutes', 'coating']}
            columnLabels={{ name: 'Name', type: 'Type', diameter: 'Diameter', flutes: 'Flutes', coating: 'Coating' }}
          />
        )}

        {activeTab === 'machines' && (
          <DatabaseView
            title="Machines Database"
            icon={Monitor}
            items={machines}
            columns={['name', 'maxRpm', 'maxFeedRate', 'horsepower', 'controller']}
            columnLabels={{ name: 'Name', maxRpm: 'Max RPM', maxFeedRate: 'Max Feed', horsepower: 'HP', controller: 'Controller' }}
          />
        )}
      </div>
    </div>
  );
}

function ResultCard({ label, value, unit, warning, className = '' }: {
  label: string;
  value: number;
  unit: string;
  warning?: boolean;
  className?: string;
}) {
  return (
    <div className={`bg-secondary/50 rounded-lg p-4 ${className}`}>
      <div className="text-sm text-muted-foreground mb-1">{label}</div>
      <div className="flex items-baseline gap-2">
        <span className={`text-2xl font-bold ${warning ? 'text-yellow-500' : 'text-primary'}`}>
          {value ?? 0}
        </span>
        <span className="text-sm text-muted-foreground">{unit}</span>
        {warning && <AlertTriangle className="w-4 h-4 text-yellow-500" />}
      </div>
    </div>
  );
}

function DatabaseView<T extends { id: string }>({ title, icon: Icon, items, columns, columnLabels }: {
  title: string;
  icon: React.ElementType;
  items: T[];
  groupBy?: string;
  columns: string[];
  columnLabels: Record<string, string>;
}) {
  const safeItems = items ?? [];

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="bg-card rounded-xl p-6 shadow-lg"
    >
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-xl font-bold flex items-center gap-2">
          <Icon className="w-6 h-6 text-primary" />
          {title}
        </h2>
        <button className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors">
          <Plus className="w-4 h-4" />
          Add Custom
        </button>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-border">
              {columns.map(col => (
                <th key={col} className="text-left py-3 px-4 text-sm font-medium text-muted-foreground">
                  {columnLabels?.[col] ?? col}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {safeItems.map((item, i) => (
              <tr key={item?.id ?? i} className="border-b border-border/50 hover:bg-secondary/30 transition-colors">
                {columns.map(col => (
                  <td key={col} className="py-3 px-4 text-sm">
                    {String((item as Record<string, unknown>)?.[col] ?? '-')}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {safeItems.length === 0 && (
        <div className="text-center text-muted-foreground py-8">
          No items found
        </div>
      )}
    </motion.div>
  );
}
