'use client';

import React, { useMemo, useState } from 'react';
import { Ticket, Upload, FileText, Settings, FileSpreadsheet } from 'lucide-react';
import * as XLSX from 'xlsx';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useGenerateCoupons } from '@/services/coupons/queries';
import { useCouponGroups } from '@/services/coupon-groups/queries';

interface Props {
  onClose: () => void;
}

type ImportTab = 'auto' | 'excel' | 'paste';
type CustomCodeRow = { code: string; officialCode?: string; examCode?: string; examOfficialCode?: string };

export default function GenerateCouponsModal({ onClose }: Props) {
  const { data: groups, isLoading: groupsLoading } = useCouponGroups(undefined, true);
  const [groupId, setGroupId] = useState('');
  const selectedGroup = useMemo(() => groups?.find((g) => g.id === groupId), [groups, groupId]);
  const isKitGroup = selectedGroup?.type === 'KIT';

  const [activeTab, setActiveTab] = useState<ImportTab>('auto');

  // Tab 1: Auto-generate state
  const [quantity, setQuantity] = useState('100');
  const [codePrefix, setCodePrefix] = useState('');

  // Tab 2 & 3: Custom imported codes state
  const [customCodes, setCustomCodes] = useState<CustomCodeRow[]>([]);
  const [pastedText, setPastedText] = useState('');
  const [error, setError] = useState<string | null>(null);

  const generateMutation = useGenerateCoupons();

  // Handle Excel/CSV Upload — columns: Code | Official Code | [Exam Code] | [Exam Official Code]
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    setError(null);
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (evt) => {
      try {
        const buffer = evt.target?.result;
        if (!buffer || !(buffer instanceof ArrayBuffer)) {
          setError('Failed to read file contents.');
          return;
        }

        const wb = XLSX.read(buffer, { type: 'array' });
        const wsname = wb.SheetNames[0];
        if (!wsname) {
          setError('Workbook contains no sheets.');
          return;
        }

        const ws = wb.Sheets[wsname];
        if (!ws) {
          setError('Failed to load sheet data.');
          return;
        }

        const data = XLSX.utils.sheet_to_json<any>(ws, { header: 1 });
        const extracted: CustomCodeRow[] = [];

        data.forEach((row: any, idx: number) => {
          if (!row || row.length === 0) return;

          const col0 = String(row[0] ?? '').trim();
          const col1 = row[1] ? String(row[1]).trim() : undefined;
          const col2 = row[2] ? String(row[2]).trim() : undefined;
          const col3 = row[3] ? String(row[3]).trim() : undefined;

          if (idx === 0 && col0.toLowerCase().includes('code')) return;

          if (col0) {
            extracted.push({
              code: col0,
              officialCode: col1,
              // Exam columns only matter for Kit groups — harmless to keep them
              // if a Normal group's sheet happens to have extra columns.
              examCode: isKitGroup ? col2 : undefined,
              examOfficialCode: isKitGroup ? col3 : undefined,
            });
          }
        });

        if (extracted.length === 0) {
          setError('No valid codes found in the uploaded file.');
          return;
        }
        if (extracted.length > 5000) {
          setError('Maximum limit is 5000 codes per import batch.');
          return;
        }

        setCustomCodes(extracted);
      } catch {
        setError('Failed to parse Excel file. Please ensure it is a valid .xlsx or .csv.');
      }
    };

    reader.readAsArrayBuffer(file);
  };

  // Process Pasted Text — "CODE,OFFICIAL_CODE" or "CODE,OFFICIAL_CODE,EXAM_CODE,EXAM_OFFICIAL_CODE"
  const handlePasteChange = (text: string) => {
    setPastedText(text);
    setError(null);

    const lines = text
      .split(/[\n,]+/)
      .map((c) => c.trim())
      .filter(Boolean);

    const extracted = lines
      .map((line) => {
        const parts = line.split(/[\t|;]/);
        return {
          code: parts[0]?.trim() || '',
          officialCode: parts[1]?.trim() || undefined,
          examCode: isKitGroup ? parts[2]?.trim() || undefined : undefined,
          examOfficialCode: isKitGroup ? parts[3]?.trim() || undefined : undefined,
        };
      })
      .filter((item) => item.code.length > 0);

    setCustomCodes(extracted);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!groupId) {
      setError('Select a coupon group first.');
      return;
    }

    if (activeTab === 'auto') {
      const qty = parseInt(quantity, 10);
      if (!qty || qty < 1 || qty > 5000) {
        setError('Enter a quantity between 1 and 5000.');
        return;
      }

      try {
        await generateMutation.mutateAsync({
          groupId,
          quantity: qty,
          codePrefix: codePrefix.trim() || undefined,
        });
        onClose();
      } catch {}
    } else {
      if (customCodes.length === 0) {
        setError('Please provide at least 1 coupon code to import.');
        return;
      }
      if (customCodes.length > 5000) {
        setError('Cannot import more than 5000 codes in a single batch.');
        return;
      }

      try {
        await generateMutation.mutateAsync({ groupId, customCodes });
        onClose();
      } catch {}
    }
  };

  return (
    <Modal onClose={onClose} icon={Ticket} iconClassName="text-primary" title="Coupon Batch Import & Generation">
      <div className="p-4 space-y-4">
        {/* STEP 0 — group must be chosen before anything else is usable */}
        <div>
          <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
            Coupon Group *
          </label>
          <select
            value={groupId}
            onChange={(e) => {
              setGroupId(e.target.value);
              setCustomCodes([]);
              setError(null);
            }}
            disabled={groupsLoading}
            className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
            required
          >
            <option value="">{groupsLoading ? 'Loading groups…' : '-- Select a group --'}</option>
            {groups?.map((g) => (
              <option key={g.id} value={g.id}>
                {g.name} {g.type === 'KIT' ? '(Kit — includes exam coupon)' : '(Normal)'}
                {g.price != null ? ` · ₹${g.price}` : ''}
              </option>
            ))}
          </select>
          {isKitGroup && (
            <p className="text-[10px] text-purple-500 mt-1 font-medium">
              Kit group selected — every coupon generated will also get an exam sub-code.
            </p>
          )}
        </div>

        {groupId && (
          <>
            <div className="flex border-b border-border/20">
              <button
                type="button"
                onClick={() => { setActiveTab('auto'); setError(null); }}
                className={`flex items-center gap-1.5 py-2 px-3 text-xs font-bold border-b-2 transition-colors cursor-pointer ${
                  activeTab === 'auto' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'
                }`}
              >
                <Settings className="h-3.5 w-3.5" /> Auto Generate
              </button>
              <button
                type="button"
                onClick={() => { setActiveTab('excel'); setError(null); }}
                className={`flex items-center gap-1.5 py-2 px-3 text-xs font-bold border-b-2 transition-colors cursor-pointer ${
                  activeTab === 'excel' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'
                }`}
              >
                <FileSpreadsheet className="h-3.5 w-3.5" /> Excel Import
              </button>
              <button
                type="button"
                onClick={() => { setActiveTab('paste'); setError(null); }}
                className={`flex items-center gap-1.5 py-2 px-3 text-xs font-bold border-b-2 transition-colors cursor-pointer ${
                  activeTab === 'paste' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'
                }`}
              >
                <FileText className="h-3.5 w-3.5" /> Copy & Paste
              </button>
            </div>

            {error && (
              <div className="p-2.5 rounded-lg border border-destructive/20 bg-destructive/5 text-destructive text-[10px] font-medium">
                {error}
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-4">
              {activeTab === 'auto' && (
                <>
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
                      Quantity to Generate *
                    </label>
                    <input
                      type="number"
                      min={1}
                      max={5000}
                      value={quantity}
                      onChange={(e) => setQuantity(e.target.value)}
                      className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
                      required
                    />
                  </div>

                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
                      Code Prefix
                    </label>
                    <input
                      type="text"
                      value={codePrefix}
                      onChange={(e) => setCodePrefix(e.target.value.toUpperCase())}
                      maxLength={8}
                      placeholder={selectedGroup?.name?.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8) || 'SSI'}
                      className="w-full text-xs font-mono font-semibold px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary uppercase"
                    />
                    <p className="text-[10px] text-muted-foreground/60 mt-1">
                      Defaults to the group name if left blank. Codes look like{' '}
                      {codePrefix || selectedGroup?.name?.toUpperCase() || 'SSI'}-{new Date().getFullYear()}-XXXXXX
                      {isKitGroup && ' — plus a separate exam code per coupon'}.
                    </p>
                  </div>
                </>
              )}

              {activeTab === 'excel' && (
                <div className="space-y-3">
                  <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80">
                    Upload Excel / CSV File (.xlsx, .xls, .csv)
                  </label>
                  <div className="border-2 border-dashed border-border/60 rounded-xl p-6 text-center bg-muted/10 hover:bg-muted/20 transition-colors">
                    <Upload className="h-6 w-6 text-primary mx-auto mb-2" />
                    <input type="file" accept=".xlsx, .xls, .csv" onChange={handleFileUpload} className="hidden" id="excel-file-input" />
                    <label htmlFor="excel-file-input" className="text-xs font-semibold text-primary hover:underline cursor-pointer block">
                      Click to browse or drag Excel file here
                    </label>
                    <p className="text-[10px] text-muted-foreground/60 mt-1">
                      Column 1: Public Code | Column 2 (Optional): Official Code
                      {isKitGroup && ' | Column 3 (Optional): Exam Code | Column 4 (Optional): Exam Official Code'}
                    </p>
                  </div>

                  {customCodes.length > 0 && (
                    <div className="p-3 bg-emerald-500/10 border border-emerald-500/20 rounded-lg text-xs text-emerald-600 font-semibold flex items-center justify-between">
                      <span>Parsed {customCodes.length} coupon codes ready to import.</span>
                      <button type="button" onClick={() => setCustomCodes([])} className="text-[10px] underline hover:text-emerald-800">
                        Clear
                      </button>
                    </div>
                  )}
                </div>
              )}

              {activeTab === 'paste' && (
                <div className="space-y-3">
                  <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80">
                    Paste Coupon Codes
                  </label>
                  <textarea
                    value={pastedText}
                    onChange={(e) => handlePasteChange(e.target.value)}
                    rows={6}
                    placeholder={
                      isKitGroup
                        ? 'CODE,OFFICIAL_CODE,EXAM_CODE,EXAM_OFFICIAL_CODE (one per line)'
                        : 'Paste list of codes separated by newlines or commas...\ne.g.\nSSI-2026-ABC123\nSSI-2026-XYZ890'
                    }
                    className="w-full text-xs font-mono p-3 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
                  />
                  {customCodes.length > 0 && (
                    <p className="text-xs text-primary font-semibold">Total Parsed Codes: {customCodes.length}</p>
                  )}
                </div>
              )}

              <div className="flex items-center justify-end gap-2 border-t border-border/10 pt-3 mt-4">
                <Button type="button" variant="ghost" onClick={onClose} className="h-8 rounded-lg px-3 text-xs font-semibold">
                  Cancel
                </Button>
                <Button type="submit" disabled={generateMutation.isPending} className="h-8 rounded-lg px-3 text-xs font-semibold shadow-sm">
                  {generateMutation.isPending
                    ? 'Processing…'
                    : activeTab === 'auto'
                    ? 'Generate Batch'
                    : `Import ${customCodes.length || ''} Coupons`}
                </Button>
              </div>
            </form>
          </>
        )}
      </div>
    </Modal>
  );
}