'use client';

import { useState, useEffect, useCallback } from 'react';
import { Copy, Star, Check, ArrowLeftRight, BarChart3 } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import SearchUnits from './SearchUnits';
import ConversionHistory from './ConversionHistory';
import VisualComparison from './VisualComparison';
import CommandPalette from '@/components/ui/CommandPalette';
import {
  getAllMeasures,
  getUnitsForMeasure,
  convertToAll,
  convertUnit,
  formatMeasureName,
  getCategoryColor,
  type Measure,
  type ConversionResult,
} from '@/lib/units';
import { parseNumberInput, formatNumber, cn } from '@/lib/utils';
import { saveToHistory, getFavorites, toggleFavorite } from '@/lib/storage';

export default function MainConverter() {
  const [selectedMeasure, setSelectedMeasure] = useState<Measure>('length');
  const [selectedUnit, setSelectedUnit] = useState<string>('m');
  const [targetUnit, setTargetUnit] = useState<string>('ft');
  const [inputValue, setInputValue] = useState<string>('1');
  const [conversions, setConversions] = useState<ConversionResult[]>([]);
  const [favorites, setFavorites] = useState<string[]>([]);
  const [copiedUnit, setCopiedUnit] = useState<string | null>(null);
  const [showVisualComparison, setShowVisualComparison] = useState(false);

  const measures = getAllMeasures();
  const units = getUnitsForMeasure(selectedMeasure);

  // Load favorites
  useEffect(() => {
    setFavorites(getFavorites());
  }, []);

  // Update conversions when input changes
  useEffect(() => {
    const numValue = parseNumberInput(inputValue);
    if (numValue !== null && selectedUnit) {
      const results = convertToAll(numValue, selectedUnit);
      setConversions(results);
    } else {
      setConversions([]);
    }
  }, [inputValue, selectedUnit]);

  // Update selected unit when measure changes
  useEffect(() => {
    const availableUnits = getUnitsForMeasure(selectedMeasure);
    if (availableUnits.length > 0) {
      setSelectedUnit(availableUnits[0]);
      setTargetUnit(availableUnits[1] || availableUnits[0]);
    }
  }, [selectedMeasure]);

  // Swap units
  const handleSwapUnits = useCallback(() => {
    const temp = selectedUnit;
    setSelectedUnit(targetUnit);
    setTargetUnit(temp);

    // Convert the value
    const numValue = parseNumberInput(inputValue);
    if (numValue !== null) {
      const converted = convertUnit(numValue, selectedUnit, targetUnit);
      setInputValue(converted.toString());
    }
  }, [selectedUnit, targetUnit, inputValue]);

  // Copy to clipboard
  const copyToClipboard = useCallback(async (value: number, unit: string) => {
    try {
      await navigator.clipboard.writeText(`${formatNumber(value)} ${unit}`);
      setCopiedUnit(unit);
      setTimeout(() => setCopiedUnit(null), 2000);
    } catch (error) {
      console.error('Failed to copy:', error);
    }
  }, []);

  // Toggle favorite
  const handleToggleFavorite = useCallback((unit: string) => {
    const isFavorite = toggleFavorite(unit);
    setFavorites(getFavorites());
  }, []);

  // Save to history when conversion happens
  useEffect(() => {
    const numValue = parseNumberInput(inputValue);
    if (numValue !== null && selectedUnit && conversions.length > 0) {
      // Save first conversion to history
      const firstConversion = conversions.find(c => c.unit !== selectedUnit);
      if (firstConversion) {
        saveToHistory({
          from: { value: numValue, unit: selectedUnit },
          to: { value: firstConversion.value, unit: firstConversion.unit },
          measure: selectedMeasure,
        });
        // Dispatch custom event for same-window updates
        window.dispatchEvent(new Event('historyUpdated'));
      }
    }
  }, [inputValue, selectedUnit, conversions, selectedMeasure]);

  // Handle search selection
  const handleSearchSelect = useCallback((unit: string, measure: Measure) => {
    setSelectedMeasure(measure);
    setSelectedUnit(unit);
  }, []);

  // Handle history selection
  const handleHistorySelect = useCallback((record: any) => {
    setInputValue(record.from.value.toString());
    setSelectedMeasure(record.measure);
    setSelectedUnit(record.from.unit);
  }, []);

  return (
    <div className="w-full max-w-6xl mx-auto space-y-6">
      {/* Command Palette */}
      <CommandPalette
        onSelectMeasure={setSelectedMeasure}
        onSelectUnit={handleSearchSelect}
      />

      {/* Search */}
      <div className="flex justify-center">
        <SearchUnits onSelectUnit={handleSearchSelect} />
      </div>

      {/* Category Selection */}
      <Card>
        <CardHeader>
          <CardTitle>Select Category</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-2">
            {measures.map((measure) => (
              <Button
                key={measure}
                variant={selectedMeasure === measure ? 'default' : 'outline'}
                size="sm"
                onClick={() => setSelectedMeasure(measure)}
                className="justify-start"
                style={{
                  backgroundColor:
                    selectedMeasure === measure
                      ? `var(--color-${getCategoryColor(measure)})`
                      : undefined,
                }}
              >
                {formatMeasureName(measure)}
              </Button>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Input Section */}
      <Card>
        <CardHeader>
          <CardTitle>Convert {formatMeasureName(selectedMeasure)}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex gap-2 items-end">
            <div className="flex-1">
              <label className="text-sm font-medium mb-2 block">Value</label>
              <Input
                type="text"
                inputMode="decimal"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                placeholder="Enter value"
                className="text-lg"
              />
            </div>
            <div className="w-40">
              <label className="text-sm font-medium mb-2 block">From</label>
              <select
                value={selectedUnit}
                onChange={(e) => setSelectedUnit(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              >
                {units.map((unit) => (
                  <option key={unit} value={unit}>
                    {unit}
                  </option>
                ))}
              </select>
            </div>
            <Button
              variant="outline"
              size="icon"
              onClick={handleSwapUnits}
              className="flex-shrink-0"
              title="Swap units"
            >
              <ArrowLeftRight className="h-4 w-4" />
            </Button>
            <div className="w-40">
              <label className="text-sm font-medium mb-2 block">To</label>
              <select
                value={targetUnit}
                onChange={(e) => setTargetUnit(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              >
                {units.map((unit) => (
                  <option key={unit} value={unit}>
                    {unit}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Quick result */}
          {parseNumberInput(inputValue) !== null && (
            <div className="p-4 rounded-lg bg-accent/50 border-l-4" style={{
              borderLeftColor: `var(--color-${getCategoryColor(selectedMeasure)})`,
            }}>
              <div className="text-sm text-muted-foreground">Result</div>
              <div className="text-3xl font-bold mt-1">
                {formatNumber(convertUnit(parseNumberInput(inputValue)!, selectedUnit, targetUnit))} {targetUnit}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Results */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>All Conversions</CardTitle>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowVisualComparison(!showVisualComparison)}
            >
              <BarChart3 className="h-4 w-4 mr-2" />
              {showVisualComparison ? 'Grid View' : 'Chart View'}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {showVisualComparison ? (
            <VisualComparison
              conversions={conversions}
              color={getCategoryColor(selectedMeasure)}
            />
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {conversions.map((conversion) => {
              const isFavorite = favorites.includes(conversion.unit);
              const isCopied = copiedUnit === conversion.unit;

              return (
                <div
                  key={conversion.unit}
                  className="group relative p-4 rounded-lg border bg-card hover:bg-accent/50 transition-colors"
                  style={{
                    borderLeftWidth: '4px',
                    borderLeftColor: `var(--color-${getCategoryColor(selectedMeasure)})`,
                  }}
                >
                  {/* Favorite & Copy buttons */}
                  <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      onClick={() => handleToggleFavorite(conversion.unit)}
                    >
                      <Star
                        className={cn(
                          'h-4 w-4',
                          isFavorite && 'fill-yellow-400 text-yellow-400'
                        )}
                      />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      onClick={() => copyToClipboard(conversion.value, conversion.unit)}
                    >
                      {isCopied ? (
                        <Check className="h-4 w-4 text-green-500" />
                      ) : (
                        <Copy className="h-4 w-4" />
                      )}
                    </Button>
                  </div>

                  <div className="text-sm text-muted-foreground mb-1">
                    {conversion.unitInfo.plural}
                  </div>
                  <div className="text-2xl font-bold">
                    {formatNumber(conversion.value)}
                  </div>
                  <div className="text-sm text-muted-foreground mt-1">
                    {conversion.unit}
                  </div>
                </div>
              );
            })}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Conversion History */}
      <ConversionHistory onSelectConversion={handleHistorySelect} />
    </div>
  );
}
