'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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import SearchUnits from './SearchUnits';
import VisualComparison from './VisualComparison';

import {
  getAllMeasures,
  getUnitsForMeasure,
  convertToAll,
  convertUnit,
  formatMeasureName,
  getCategoryColor,
  getCategoryColorHex,
  type Measure,
  type ConversionResult,
} from '@/lib/units/units';
import { parseNumberInput, formatNumber, cn } from '@/lib/utils';
import { getFavorites, toggleFavorite } from '@/lib/units/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 [isDragging, setIsDragging] = 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());
  }, []);

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

  // Handle value change from draggable bars
  const handleValueChange = useCallback((value: number, unit: string, dragging: boolean) => {
    setIsDragging(dragging);

    // Convert the dragged unit's value back to the currently selected unit
    // This keeps the source unit stable while updating the value
    const convertedValue = convertUnit(value, unit, selectedUnit);
    setInputValue(convertedValue.toString());
    // Keep selectedUnit unchanged
  }, [selectedUnit]);

  return (
    <div className="w-full space-y-8">

      {/* Quick Access Row */}
      <div className="flex flex-col md:flex-row md:items-center gap-4 justify-between bg-card p-4 rounded-lg border">
        <div className="flex-1">
          <SearchUnits onSelectUnit={handleSearchSelect} />
        </div>

        <div className="w-full md:w-64 shrink-0">
          <Select
            value={selectedMeasure}
            onValueChange={(value) => setSelectedMeasure(value as Measure)}
          >
            <SelectTrigger
              className="w-full"
              style={{
                borderLeft: `4px solid ${getCategoryColorHex(selectedMeasure)}`,
              }}
            >
              <SelectValue placeholder="Measure" />
            </SelectTrigger>
            <SelectContent>
              {measures.map((measure) => (
                <SelectItem key={measure} value={measure}>
                  {formatMeasureName(measure)}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Main Converter Card */}
      <Card>
        <CardHeader>
          <CardTitle>Convert {formatMeasureName(selectedMeasure)}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6 pt-0">
          {/* Input row, stacks vertically on mobile, horizontal on desktop */}
          <div className="flex flex-col gap-4 md:flex-row md:items-end md:gap-2">
            {/* Value Input */}
            <div className="flex-1 w-full">
              <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={cn("text-lg", "w-full", "max-w-full")}
              />
            </div>
            {/* From Unit Select */}
            <div className="w-full md:w-40">
              <label className="text-sm font-medium mb-2 block">From</label>
              <Select
                value={selectedUnit}
                onValueChange={(value) => setSelectedUnit(value)}
              >
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="From" />
                </SelectTrigger>
                <SelectContent>
                  {units.map((unit) => (
                    <SelectItem key={unit} value={unit}>
                      {unit}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {/* Swap Button */}
            <Button
              variant="outline"
              size="icon"
              onClick={handleSwapUnits}
              className="flex-shrink-0 w-full md:w-40" // Make button full width on mobile too
              title="Swap units"
            >
              <ArrowLeftRight className="h-4 w-4" />
            </Button>
            {/* To Unit Select */}
            <div className="w-full md:w-40">
              <label className="text-sm font-medium mb-2 block">To</label>
              <Select
                value={targetUnit}
                onValueChange={(value) => setTargetUnit(value)}
              >
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="To" />
                </SelectTrigger>
                <SelectContent>
                  {units.map((unit) => (
                    <SelectItem key={unit} value={unit}>
                      {unit}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* Quick result */}
          {parseNumberInput(inputValue) !== null && (
            <div className="p-4 rounded-lg bg-accent/50 border-l-4" style={{
              borderLeftColor: getCategoryColorHex(selectedMeasure),
            }}>
              <div className="text-sm text-muted-foreground">Result</div>
              <div className="text-3xl font-bold mt-1" style={{
                color: getCategoryColorHex(selectedMeasure),
              }}>
                {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={getCategoryColorHex(selectedMeasure)}
              onValueChange={handleValueChange}
            />
          ) : (
            <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: getCategoryColorHex(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>
    </div>
  );
}
