'use client';

import { useState, useEffect, useCallback } from 'react';
import { ArrowLeftRight, BarChart3 } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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,
  type Measure,
  type ConversionResult,
} from '@/lib/units/units';
import { parseNumberInput, formatNumber, cn } from '@/lib/utils';

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 [showVisualComparison, setShowVisualComparison] = useState(false);
  const [isDragging, setIsDragging] = useState(false);

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

  // 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]);

  // 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-6">

      {/* Quick Access Row */}
      <Card>
        <CardContent className="flex flex-col md:flex-row md:items-center gap-3 justify-between">
          <div className="flex-1">
            <SearchUnits onSelectUnit={handleSearchSelect} />
          </div>
          <div className="w-full md:w-56 shrink-0">
            <Select
              value={selectedMeasure}
              onValueChange={(value) => setSelectedMeasure(value as Measure)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Measure" />
              </SelectTrigger>
              <SelectContent>
                {measures.map((measure) => (
                  <SelectItem key={measure} value={measure}>
                    {formatMeasureName(measure)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Main Converter Card */}
      <Card>
        <CardHeader>
          <CardTitle>Convert {formatMeasureName(selectedMeasure)}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-col gap-3 md:flex-row md:items-end md:gap-2">
            <div className="flex-1 w-full">
              <Label className="text-xs mb-1.5">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>
            <div className="w-full md:w-36">
              <Label className="text-xs mb-1.5">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>
            <Button
              variant="outline"
              size="icon"
              onClick={handleSwapUnits}
              className="shrink-0 w-full md:w-7"
              title="Swap units"
            >
              <ArrowLeftRight className="h-3.5 w-3.5" />
            </Button>
            <div className="w-full md:w-36">
              <Label className="text-xs mb-1.5">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>

          {parseNumberInput(inputValue) !== null && (
            <div className="p-3 rounded-lg bg-primary/5 border border-primary/15">
              <div className="text-xs text-muted-foreground mb-0.5">Result</div>
              <div className="text-2xl font-bold text-primary tabular-nums">
                {formatNumber(convertUnit(parseNumberInput(inputValue)!, selectedUnit, targetUnit))} <span className="text-base font-medium text-muted-foreground">{targetUnit}</span>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Results */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>All Conversions</CardTitle>
            <Button
              variant="outline"
              size="xs"
              onClick={() => setShowVisualComparison(!showVisualComparison)}
            >
              <BarChart3 className="h-3 w-3 mr-1" />
              {showVisualComparison ? 'Grid' : 'Chart'}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {showVisualComparison ? (
            <VisualComparison
              conversions={conversions}
              onValueChange={handleValueChange}
            />
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
              {conversions.map((conversion) => (
                <div
                  key={conversion.unit}
                  className="p-3 rounded-lg border border-border/50 hover:border-primary/30 transition-colors"
                >
                  <div className="text-xs text-muted-foreground">{conversion.unitInfo.plural}</div>
                  <div className="text-lg font-bold tabular-nums mt-0.5">{formatNumber(conversion.value)}</div>
                  <div className="text-xs text-muted-foreground">{conversion.unit}</div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
