'use client';

import { useState, useEffect } from 'react';
import { Battery, X } from 'lucide-react';
import toast from 'react-hot-toast';

interface AssignBatteryModalProps {
  isOpen: boolean;
  onClose: () => void;
  investor: any;
  batteries: any[];
  unassignedBatteries: any[];
  preselectedPlanId?: string;
  onAssign: (planId: string, batteryIds: string[]) => void;
}

export default function AssignBatteryModal({
  isOpen,
  onClose,
  investor,
  batteries,
  unassignedBatteries,
  preselectedPlanId = '',
  onAssign
}: AssignBatteryModalProps) {
  const [selectedPlanId, setSelectedPlanId] = useState(preselectedPlanId);
  const [selectedBatteryIds, setSelectedBatteryIds] = useState<string[]>([]);

  useEffect(() => {
    if (isOpen) {
      setSelectedPlanId(preselectedPlanId);
      setSelectedBatteryIds([]);
    }
  }, [isOpen, preselectedPlanId]);

  if (!isOpen || !investor) return null;

  const getPlanTargetAssetCount = (plan: any) => {
    if (!plan) return 1;
    if (plan.assetType === 'battery' || plan.planName?.toLowerCase().includes('battery')) {
      if (plan.id === 'ip3') return 2;
      const nameLower = plan.planName?.toLowerCase() || '';
      if (nameLower.includes('10')) return 10;
      if (nameLower.includes('5')) return 5;
      return 1;
    } else {
      if (plan.id === 'ip1' || plan.id === 'ip2') return 1;
      const nameLower = plan.planName?.toLowerCase() || '';
      if (nameLower.includes('10')) return 10;
      if (nameLower.includes('5')) return 5;
      return 1;
    }
  };

  const selectedPlan = investor.investments?.find((inv: any) => inv.id === selectedPlanId);
  const assignedCount = selectedPlan ? batteries.filter(b => b.investmentId === selectedPlan.id).length : 0;
  const targetCount = selectedPlan ? getPlanTargetAssetCount(selectedPlan) : 0;
  const remainingCapacity = selectedPlan ? Math.max(0, targetCount - assignedCount) : 0;

  const handleAssignSubmit = () => {
    if (!selectedPlanId) {
      toast.error('Please select an investment plan');
      return;
    }
    if (selectedBatteryIds.length === 0) {
      toast.error('Please select at least one battery');
      return;
    }
    onAssign(selectedPlanId, selectedBatteryIds);
    onClose();
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-md overflow-hidden flex flex-col">
        <div className="p-5 border-b border-emerald-100 bg-emerald-50 flex items-center justify-between">
          <h2 className="text-lg font-bold text-emerald-800 flex items-center gap-2">
            <Battery className="w-5 h-5 text-emerald-600 animate-bounce" />
            Assign Battery to Partner
          </h2>
          <button onClick={onClose} className="p-2 hover:bg-emerald-100 rounded-lg text-emerald-600">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-5 space-y-4 overflow-y-auto max-h-[70vh]">
          <div>
            <label className="text-sm font-medium text-slate-600 mb-1.5 block">Link to Investment Plan *</label>
            <select
              value={selectedPlanId}
              disabled={!!preselectedPlanId}
              onChange={(e) => {
                setSelectedPlanId(e.target.value);
                setSelectedBatteryIds([]);
              }}
              className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-emerald-500 disabled:bg-slate-50 disabled:text-slate-500"
            >
              <option value="">Select plan</option>
              {investor.investments?.filter((inv: any) => inv.assetType === 'battery' || inv.planName.toLowerCase().includes('battery')).map((inv: any) => {
                const curAssigned = batteries.filter(b => b.investmentId === inv.id).length;
                const target = getPlanTargetAssetCount(inv);
                const rem = Math.max(0, target - curAssigned);
                return (
                  <option key={inv.id} value={inv.id}>
                    {inv.planName} (Remaining: {rem} / {target} Pack{target !== 1 ? 's' : ''})
                  </option>
                );
              })}
            </select>
          </div>

          {selectedPlanId && (
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <label className="text-sm font-semibold text-slate-700 block">Select Battery Pack(s) *</label>
                <span className="text-xs font-bold text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded-full">
                  Selected: {selectedBatteryIds.length} / {remainingCapacity}
                </span>
              </div>

              {remainingCapacity === 0 ? (
                <div className="p-3 text-center text-xs text-amber-700 bg-amber-50 rounded-lg border border-amber-200">
                  This plan has reached its full capacity of {targetCount} battery pack(s). Unassign some batteries first to assign new ones.
                </div>
              ) : (
                <div className="border border-slate-200 rounded-lg max-h-56 overflow-y-auto divide-y divide-slate-100">
                  {unassignedBatteries.map(bat => {
                    const isChecked = selectedBatteryIds.includes(bat.id);
                    const isDisabled = !isChecked && selectedBatteryIds.length >= remainingCapacity;
                    return (
                      <label
                        key={bat.id}
                        className={`flex items-center justify-between p-3 cursor-pointer text-sm transition-colors ${
                          isChecked ? 'bg-emerald-50/50' : isDisabled ? 'opacity-50 cursor-not-allowed bg-slate-50' : 'hover:bg-slate-50'
                        }`}
                      >
                        <div className="flex items-center gap-2.5">
                          <input
                            type="checkbox"
                            checked={isChecked}
                            disabled={isDisabled}
                            onChange={(e) => {
                              if (e.target.checked) {
                                if (selectedBatteryIds.length < remainingCapacity) {
                                  setSelectedBatteryIds([...selectedBatteryIds, bat.id]);
                                } else {
                                  toast.error(`Cannot select more than ${remainingCapacity} batteries`);
                                }
                              } else {
                                setSelectedBatteryIds(selectedBatteryIds.filter(id => id !== bat.id));
                              }
                            }}
                            className="rounded text-emerald-600 focus:ring-emerald-500 border-slate-300 w-4 h-4"
                          />
                          <div>
                            <p className="font-semibold text-slate-800">{bat.brand} {bat.model}</p>
                            <p className="text-xs text-slate-500">SN: {bat.serialNumber}</p>
                          </div>
                        </div>
                        <span className="text-slate-600 font-medium text-xs">৳{bat.purchasePrice?.toLocaleString() || 0}</span>
                      </label>
                    );
                  })}
                  {unassignedBatteries.length === 0 && (
                    <div className="p-4 text-center text-slate-400 text-sm">No unassigned batteries available</div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>

        <div className="p-5 border-t border-slate-100 flex justify-end gap-3 bg-slate-50">
          <button
            onClick={onClose}
            className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm font-semibold hover:bg-slate-100 bg-white"
          >
            Cancel
          </button>
          <button
            onClick={handleAssignSubmit}
            disabled={!selectedPlanId || selectedBatteryIds.length === 0}
            className="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-semibold hover:bg-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm transition-colors"
          >
            Assign {selectedBatteryIds.length > 0 ? `${selectedBatteryIds.length} Battery/ies` : 'Battery'}
          </button>
        </div>
      </div>
    </div>
  );
}
