
"use client";

import React, { useState } from 'react';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Terminal, Info } from "lucide-react";
import type { DataItem, ItemTypeValue } from '@/types';
import { parseLocationRange } from '@/lib/locationUtils';

interface ManualBulkInputProps {
  onBulkAdd: (items: Partial<DataItem>[]) => void;
}

export function ManualBulkInput({ onBulkAdd }: ManualBulkInputProps) {
  const [bulkText, setBulkText] = useState('');
  const [error, setError] = useState<string | null>(null);

  const handleAddBulk = () => {
    setError(null);
    if (!bulkText.trim()) {
      setError("Input cannot be empty.");
      return;
    }

    const lines = bulkText.trim().split('\n').filter(line => line.trim() !== '');
    const newItems: Partial<DataItem>[] = [];
    let lineErrors: string[] = [];

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      const values = line.split('\t').map(v => v.trim()); // Split by TAB

      // Expected: Range Start, Range End, Type, Aisle, Description
      if (values.length < 3 || values.length > 5) {
        lineErrors.push(`Line ${i + 1} ("${line}"): Incorrect number of columns. Expected 3 to 5 columns (Range Start, Range End, Type, optional Aisle, optional Description), but got ${values.length}.`);
        continue;
      }

      const rangeStartStr = values[0];
      const rangeEndStr = values[1];
      const typeStr = values[2];
      const aisleStr = values.length > 3 ? values[3] : '';
      const descriptionStr = values.length > 4 ? values[4] : '';

      if (!rangeStartStr) {
        lineErrors.push(`Line ${i + 1} ("${line}"): Range Start (column 1) is missing.`);
        continue;
      }
      if (!typeStr) {
        lineErrors.push(`Line ${i + 1} ("${line}"): Type (column 3) is missing or empty.`);
        continue;
      }

      const itemType = typeStr as ItemTypeValue;

      let locationRangeInputStr = rangeStartStr;
      if (rangeEndStr && rangeEndStr.trim() !== "" && rangeEndStr !== rangeStartStr) {
        locationRangeInputStr = `${rangeStartStr}-${rangeEndStr}`;
      }

      const locationsToProcess = parseLocationRange(locationRangeInputStr);
      let effectiveLocations: (string | number | undefined)[];

      if (locationRangeInputStr.trim() === "") {
          effectiveLocations = [undefined];
      } else if (locationsToProcess.length === 0) {
          lineErrors.push(`Line ${i + 1} ("${line}"): Invalid location constructed from Range Start "${rangeStartStr}" and Range End "${rangeEndStr}" (parsed as "${locationRangeInputStr}").`);
          continue;
      } else {
          effectiveLocations = locationsToProcess;
      }

      for (const loc of effectiveLocations) {
        newItems.push({
          location: loc,
          aisle: aisleStr || undefined,
          sisel: '',
          dept: '',
          description: descriptionStr || undefined,
          type: itemType,
          originalRangeInput: locationRangeInputStr.trim() === "" ? "" : locationRangeInputStr, // Store the constructed range string
        });
      }
    }

    if (lineErrors.length > 0) {
        setError(lineErrors.join('\n'));
        return;
    }

    if (newItems.length === 0 && lines.length > 0) {
      setError("No valid data items could be parsed. Please check format. Ensure Range Start and Type are provided for each line.");
      return;
    }

    if (newItems.length > 0) {
      onBulkAdd(newItems);
      setBulkText('');
    }
  };

  return (
    <div className="space-y-4">
       <Alert>
        <Info className="h-4 w-4" />
        <AlertTitle>Bulk Input from Excel</AlertTitle>
        <AlertDescription>
          Paste data from Excel.
        </AlertDescription>
      </Alert>
      <Textarea
        value={bulkText}
        onChange={(e) => setBulkText(e.target.value)}
        placeholder="Paste tab-separated data. Columns: Range Start, Range End, Type, Aisle, Description"
        rows={6}
        className="bg-background"
      />
      {error && (
        <Alert variant="destructive" className="whitespace-pre-line">
          <Terminal className="h-4 w-4" />
          <AlertTitle>Error Parsing Bulk Input</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}
      <Button onClick={handleAddBulk} className="w-full sm:w-auto">
        Add Bulk Data to List
      </Button>
    </div>
  );
}
