'use client';

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

interface AssignBikeModalProps {
  isOpen: boolean;
  onClose: () => void;
  investor: any;
  bikes: any[];
  preselectedPlanId?: string;
  onAssign: (planId: string, bikeIds: string[]) => void;
}

export default function AssignBikeModal({
  isOpen,
  onClose,
  investor,
  bikes,
  preselectedPlanId = '',
  onAssign
}: AssignBikeModalProps) {
  const [selectedPlanId, setSelectedPlanId] = useState(preselectedPlanId);
  const [selectedBikeIds, setSelectedBikeIds] = useState<string[]>([]);

  useEffect(() => {
    if (isOpen) {
      setSelectedPlanId(preselectedPlanId);
      setSelectedBikeIds([]);
    }
  }, [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 ? bikes.filter(b => b.investmentId === selectedPlan.id).length : 0;
  const targetCount = selectedPlan ? getPlanTargetAssetCount(selectedPlan) : 0;
  const remainingCapacity = selectedPlan ? Math.max(0, targetCount - assignedCount) : 0;

  const availableBikes = bikes.filter(b => !b.investorId && b.status === 'available');

  const handleAssignSubmit = () => {
    if (!selectedPlanId) {
      toast.error('Please select an investment plan');
      return;
    }
    if (selectedBikeIds.length === 0) {
      toast.error('Please select at least one bike');
      return;
    }
    onAssign(selectedPlanId, selectedBikeIds);
    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-slate-100 flex items-center justify-between">
          <h2 className="text-lg font-bold text-investor flex items-center gap-2">
            <Bike className="w-5 h-5 text-investor animate-bounce" />
            Assign Bike to Investor
          </h2>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 rounded-lg">
            <X className="w-5 h-5 text-slate-400" />
          </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">Select Investment Plan *</label>
            <select
              value={selectedPlanId}
              disabled={!!preselectedPlanId}
              onChange={(e) => {
                setSelectedPlanId(e.target.value);
                setSelectedBikeIds([]);
              }}
              className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-investor disabled:bg-slate-50 disabled:text-slate-500"
            >
              <option value="">Choose an active plan</option>
              {investor.investments?.filter((inv: any) => inv.assetType === 'bike' || !inv.assetType || inv.planName.toLowerCase().includes('ev') || inv.planName.toLowerCase().includes('bike')).map((inv: any) => {
                const curAssigned = bikes.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} Bike{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 Bike(s) *</label>
                <span className="text-xs font-bold text-investor bg-investor/10 px-2 py-0.5 rounded-full">
                  Selected: {selectedBikeIds.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} bike(s). Unassign some bikes first to assign new ones.
                </div>
              ) : (
                <div className="border border-slate-200 rounded-lg max-h-48 overflow-y-auto divide-y divide-slate-100">
                  {availableBikes.map(bike => {
                    const isChecked = selectedBikeIds.includes(bike.id);
                    const isDisabled = !isChecked && selectedBikeIds.length >= remainingCapacity;
                    return (
                      <label
                        key={bike.id}
                        className={`flex items-center justify-between p-3 cursor-pointer text-sm transition-colors ${
                          isChecked ? 'bg-investor/5' : 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 (selectedBikeIds.length < remainingCapacity) {
                                  setSelectedBikeIds([...selectedBikeIds, bike.id]);
                                } else {
                                  toast.error(`Cannot select more than ${remainingCapacity} bikes`);
                                }
                              } else {
                                setSelectedBikeIds(selectedBikeIds.filter(id => id !== bike.id));
                              }
                            }}
                            className="rounded text-investor focus:ring-investor border-slate-300 w-4 h-4"
                          />
                          <div>
                            <p className="font-semibold text-slate-800">{bike.model} • {bike.brand}</p>
                            <p className="text-xs text-slate-500">{bike.plateNumber}</p>
                          </div>
                        </div>
                        <span className="text-slate-600 font-medium text-xs">৳{bike.purchasePrice?.toLocaleString() || 0}</span>
                      </label>
                    );
                  })}
                  {availableBikes.length === 0 && (
                    <div className="p-4 text-center text-slate-400 text-sm">No unassigned available bikes found</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 || selectedBikeIds.length === 0}
            className="px-4 py-2 bg-investor text-white rounded-lg text-sm font-semibold hover:bg-investor-dark disabled:opacity-50 disabled:cursor-not-allowed shadow-sm transition-colors"
          >
            Assign {selectedBikeIds.length > 0 ? `${selectedBikeIds.length} Bike(s)` : 'Bike'}
          </button>
        </div>
      </div>
    </div>
  );
}
