import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Hash,
  Plus,
  Trash2,
  Edit2,
  Loader2,
  AlertCircle,
  Tag,
  Search,
  ChevronLeft,
  ChevronRight,
  SearchX
} from 'lucide-react';
import {
  getAllHsnSacCodes,
  createHsnSacCode,
  updateHsnSacCode,
  deleteHsnSacCode,
  toggleHsnSacCodeActive,
  HsnSacCode,
  CodeType
} from '@/services/hsnSacCodeApi';
import { toast } from 'sonner';
import { validateHSNSAC } from '@/utils/validationUtils';

export function HsnSacCodeManager() {
  const [codes, setCodes] = useState<HsnSacCode[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [editingCode, setEditingCode] = useState<HsnSacCode | null>(null);
  const [error, setError] = useState<string | null>(null);
  
  // Pagination & Search State
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalRecords, setTotalRecords] = useState(0);
  const [limit] = useState(10);
  const [searchQuery, setSearchQuery] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  
  const [formData, setFormData] = useState({
    code: '',
    type: 'HSN' as CodeType,
    gstRate: '',
    description: '',
    isActive: true
  });

  // Debounce search query
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchQuery);
      setCurrentPage(1); // Reset to first page on new search
    }, 500);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  useEffect(() => {
    loadCodes();
  }, [currentPage, debouncedSearch]);

  const loadCodes = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await getAllHsnSacCodes(false, currentPage, limit, debouncedSearch);
      setCodes(response.codes);
      setTotalPages(response.pagination.totalPages);
      setTotalRecords(response.pagination.totalRecords);
    } catch (err: any) {
      const errorMsg = err.response?.data?.error || 'Failed to load HSN/SAC codes';
      setError(errorMsg);
      toast.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setFormData({
      code: '',
      type: 'HSN',
      gstRate: '',
      description: '',
      isActive: true
    });
    setEditingCode(null);
    setShowAddDialog(true);
  };

  const handleEdit = (code: HsnSacCode) => {
    setFormData({
      code: code.code,
      type: code.type,
      gstRate: code.gstRate?.toString() || '',
      description: code.description || '',
      isActive: code.isActive
    });
    setEditingCode(code);
    setShowAddDialog(true);
  };

  const handleSave = async () => {
    try {
      setError(null);

      if (!formData.code.trim() || !formData.type) {
        setError('Code and Type are required');
        toast.error('Please fill in required fields');
        return;
      }

      const { isValid, message } = validateHSNSAC(formData.code, formData.type === 'SAC');
      if (!isValid) {
        setError(message);
        toast.error(message);
        return;
      }

      const payload = {
        code: formData.code.trim(),
        type: formData.type,
        gstRate: formData.gstRate ? parseFloat(formData.gstRate) : undefined,
        description: formData.description.trim() || undefined,
        isActive: formData.isActive
      };

      if (editingCode) {
        await updateHsnSacCode(editingCode.id, payload);
        toast.success(`${formData.type} code updated successfully`);
      } else {
        await createHsnSacCode(payload);
        toast.success(`${formData.type} code created successfully`);
      }

      await loadCodes();
      setShowAddDialog(false);
    } catch (err: any) {
      const errorMsg = err.response?.data?.error || 'Failed to save code';
      setError(errorMsg);
      toast.error(errorMsg);
    }
  };

  const handleDelete = async (code: HsnSacCode) => {
    if (!confirm(`Delete ${code.type} code "${code.code}"?`)) {
      return;
    }

    try {
      setError(null);
      await deleteHsnSacCode(code.id);
      toast.success('Code deleted successfully');
      await loadCodes();
    } catch (err: any) {
      const errorMsg = err.response?.data?.error || 'Failed to delete code';
      setError(errorMsg);
      toast.error(errorMsg);
    }
  };

  const handleToggle = async (id: string) => {
    try {
      await toggleHsnSacCodeActive(id);
      await loadCodes();
      toast.success('Status updated successfully');
    } catch (err: any) {
      toast.error('Failed to toggle status');
    }
  };


  return (
    <div className="space-y-6">
      {/* Error Message */}
      {error && (
        <div className="p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300">
          <div className="p-1.5 bg-red-500 rounded-md">
            <AlertCircle className="w-4 h-4 text-white shrink-0" />
          </div>
          <p className="text-sm font-medium text-red-900">{error}</p>
          <Button
            size="sm"
            variant="ghost"
            onClick={() => setError(null)}
            className="ml-auto hover:bg-red-100"
          >
            Dismiss
          </Button>
        </div>
      )}

      {/* Header */}
      <Card className="shadow-lg border-0 rounded-md">
        <CardHeader className="border-b border-slate-100 py-4 sm:py-5">
          <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <div className="p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md">
                <Hash className="w-5 h-5 text-white" />
              </div>
              <div>
                <CardTitle className="text-lg sm:text-xl font-semibold text-slate-900">HSN/SAC Codes</CardTitle>
                <CardDescription className="text-xs sm:text-sm">
                  Manage HSN/SAC codes and associated GST rates ({totalRecords} total)
                </CardDescription>
              </div>
            </div>
            
            <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 w-full lg:w-auto">
              {/* Search Bar */}
              <div className="relative flex-1 sm:w-64">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <Input
                  placeholder="Search code or description..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-9 bg-slate-50 border-slate-200 focus:bg-white transition-all text-sm"
                />
              </div>

              <Button
                onClick={handleAdd}
                className="gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm whitespace-nowrap"
              >
                <Plus className="w-4 h-4" />
                <span>Add New Code</span>
              </Button>
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
        </div>
      ) : codes.length === 0 ? (
        <Card className="shadow-lg border-0 rounded-md">
          <CardContent className="p-12 text-center">
            <div className="p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4">
              {debouncedSearch ? <SearchX className="w-10 h-10 text-slate-400" /> : <Hash className="w-10 h-10 text-slate-400" />}
            </div>
            <p className="text-slate-700 font-medium text-lg">
              {debouncedSearch ? `No results for "${debouncedSearch}"` : 'No HSN/SAC codes found'}
            </p>
            <p className="text-sm text-slate-500 mt-2 mb-6">
              {debouncedSearch ? 'Try a different search term' : 'Add codes to use in dealer claims'}
            </p>
            {debouncedSearch ? (
              <Button onClick={() => setSearchQuery('')} variant="outline">Clear Search</Button>
            ) : (
              <Button
                onClick={handleAdd}
                variant="outline"
                className="gap-2 border-slate-300 hover:bg-slate-50"
              >
                <Plus className="w-4 h-4" />
                Add First Code
              </Button>
            )}
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-6">
          {/* Results Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {codes.map(code => (
              <CodeCard 
                key={code.id} 
                code={code} 
                onEdit={() => handleEdit(code)} 
                onDelete={() => handleDelete(code)}
                onToggle={() => handleToggle(code.id)}
              />
            ))}
          </div>

          {/* Pagination Controls */}
          {totalPages > 1 && (
            <div className="flex flex-col sm:flex-row items-center justify-between gap-4 pt-4 border-t border-slate-100">
              <p className="text-sm text-slate-500 order-2 sm:order-1">
                Showing <span className="font-medium">{(currentPage - 1) * limit + 1}</span> to{' '}
                <span className="font-medium">
                  {Math.min(currentPage * limit, totalRecords)}
                </span>{' '}
                of <span className="font-medium">{totalRecords}</span> results
              </p>
              
              <div className="flex items-center gap-2 order-1 sm:order-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                  disabled={currentPage === 1}
                  className="gap-1 h-9"
                >
                  <ChevronLeft className="w-4 h-4" />
                  <span>Previous</span>
                </Button>
                
                <div className="flex items-center gap-1">
                  {[...Array(totalPages)].map((_, i) => {
                    const pageNum = i + 1;
                    // Show first, last, and current page with neighbors logic if many pages
                    if (
                      totalPages <= 7 ||
                      pageNum === 1 ||
                      pageNum === totalPages ||
                      (pageNum >= currentPage - 1 && pageNum <= currentPage + 1)
                    ) {
                      return (
                        <Button
                          key={pageNum}
                          variant={currentPage === pageNum ? 'default' : 'outline'}
                          size="sm"
                          onClick={() => setCurrentPage(pageNum)}
                          className={`w-9 h-9 p-0 ${currentPage === pageNum ? 'bg-slate-800' : 'text-slate-600'}`}
                        >
                          {pageNum}
                        </Button>
                      );
                    } else if (
                      (pageNum === currentPage - 2 && pageNum > 1) ||
                      (pageNum === currentPage + 2 && pageNum < totalPages)
                    ) {
                      return <span key={pageNum} className="px-1 text-slate-400">...</span>;
                    }
                    return null;
                  })}
                </div>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                  disabled={currentPage === totalPages}
                  className="gap-1 h-9"
                >
                  <span>Next</span>
                  <ChevronRight className="w-4 h-4" />
                </Button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Dialog */}
      <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>{editingCode ? 'Edit Code' : 'Add New HSN/SAC Code'}</DialogTitle>
            <DialogDescription>
              Enter the details for recovery or claim code
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="type">Type <span className="text-red-500">*</span></Label>
                <Select
                  value={formData.type}
                  onValueChange={(val: CodeType) => setFormData({ ...formData, type: val })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="HSN">HSN</SelectItem>
                    <SelectItem value="SAC">SAC</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2 relative pb-5">
                <Label htmlFor="code">Code <span className="text-red-500">*</span></Label>
                <Input
                  id="code"
                  placeholder="e.g., 998311"
                  value={formData.code}
                  onChange={e => setFormData({ ...formData, code: e.target.value })}
                  className={!validateHSNSAC(formData.code, formData.type === 'SAC').isValid ? 'border-red-500' : ''}
                />
                {!validateHSNSAC(formData.code, formData.type === 'SAC').isValid && formData.code && (
                  <p className="text-[10px] text-red-500 absolute left-0 bottom-0 leading-tight">
                    {validateHSNSAC(formData.code, formData.type === 'SAC').message}
                  </p>
                )}
              </div>
            </div>

{/* Hide GST rate input for now
            <div className="space-y-2">
              <Label htmlFor="gstRate">GST Rate (%)</Label>
              <Input
                id="gstRate"
                type="number"
                step="0.01"
                placeholder="e.g., 18.00"
                value={formData.gstRate}
                onChange={e => setFormData({ ...formData, gstRate: e.target.value })}
              />
            </div>
            */}

            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Input
                id="description"
                placeholder="Brief description of the code"
                value={formData.description}
                onChange={e => setFormData({ ...formData, description: e.target.value })}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAddDialog(false)}>Cancel</Button>
            <Button onClick={handleSave} className="bg-re-green hover:bg-re-green/90 text-white">
              {editingCode ? 'Update Code' : 'Create Code'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function CodeCard({ code, onEdit, onDelete, onToggle }: { 
  code: HsnSacCode, 
  onEdit: () => void, 
  onDelete: () => void,
  onToggle: () => void 
}) {
  return (
    <div className={`p-4 rounded-lg border flex flex-col justify-between gap-4 transition-all hover:shadow-md ${code.isActive ? 'bg-white border-slate-200' : 'bg-slate-50/50 border-slate-100 grayscale-[0.5]'}`}>
      <div className="flex justify-between items-start">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-md ${code.type === 'HSN' ? 'bg-blue-50 text-blue-600' : 'bg-purple-50 text-purple-600'}`}>
            <Tag className="w-5 h-5" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">{code.type}</span>
              <h4 className="font-bold text-slate-900">{code.code}</h4>
            </div>
            {code.description && <p className="text-xs text-slate-500 mt-0.5 line-clamp-1">{code.description}</p>}
          </div>
        </div>
        <div className="flex items-center gap-1">
          {/* GST rate badge hidden for now */}
        </div>
      </div>
      
      <div className="flex items-center justify-between border-t border-slate-50 pt-3 mt-1">
        <div className="flex items-center gap-2">
          <Button 
            variant="ghost" 
            size="sm" 
            className="h-8 w-8 p-0 text-slate-400 hover:text-blue-600 hover:bg-blue-50"
            onClick={onEdit}
          >
            <Edit2 className="w-4 h-4" />
          </Button>
          <Button 
            variant="ghost" 
            size="sm" 
            className="h-8 w-8 p-0 text-slate-400 hover:text-red-600 hover:bg-red-50"
            onClick={onDelete}
          >
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>
        
        <Button 
          variant="ghost" 
          size="sm" 
          className={`text-[10px] font-bold uppercase tracking-widest ${code.isActive ? 'text-amber-600' : 'text-green-600'}`}
          onClick={onToggle}
        >
          {code.isActive ? 'Deactivate' : 'Activate'}
        </Button>
      </div>
    </div>
  );
}
