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 { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  FileText,
  Plus,
  Trash2,
  Edit2,
  Loader2,
  AlertCircle,
  CheckCircle,
} from 'lucide-react';
import {
  getAllActivityTypes,
  createActivityType,
  updateActivityType,
  deleteActivityType,
  ActivityType
} from '@/services/adminApi';
import { toast } from 'sonner';

export function ActivityTypeManager() {
  const [activityTypes, setActivityTypes] = useState<ActivityType[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [editingActivityType, setEditingActivityType] = useState<ActivityType | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    title: '',
    itemCode: '',
    taxationType: '',
    sapRefNo: '',
    creditPostingOn: ''
  });

  useEffect(() => {
    loadActivityTypes();
  }, []);

  const loadActivityTypes = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getAllActivityTypes(false); // Get all including inactive
      setActivityTypes(data);
    } catch (err: any) {
      const errorMsg = err.response?.data?.error || 'Failed to load activity types';
      setError(errorMsg);
      toast.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setFormData({
      title: '',
      itemCode: '',
      taxationType: '',
      sapRefNo: '',
      creditPostingOn: ''
    });
    setEditingActivityType(null);
    setShowAddDialog(true);
  };

  const handleEdit = (activityType: ActivityType) => {
    setFormData({
      title: activityType.title,
      itemCode: activityType.itemCode || '',
      taxationType: activityType.taxationType || '',
      sapRefNo: activityType.sapRefNo || '',
      creditPostingOn: activityType.creditPostingOn || ''
    });
    setEditingActivityType(activityType);
    setShowAddDialog(true);
  };

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

      if (!formData.title.trim() || !formData.taxationType.trim() || !formData.sapRefNo.trim() || !formData.creditPostingOn.trim()) {
        setError('Title, Taxation Type, Credit Posting On, and Claim Document Type (SAP Ref) are required');
        toast.error('Please fill in all mandatory fields');
        return;
      }

      const payload: Partial<ActivityType> = {
        title: formData.title.trim(),
        itemCode: formData.itemCode.trim() || null,
        taxationType: formData.taxationType.trim(),
        sapRefNo: formData.sapRefNo.trim(),
        creditPostingOn: formData.creditPostingOn.trim()
      };

      if (editingActivityType) {
        // Update existing
        await updateActivityType(editingActivityType.activityTypeId, payload);
        toast.success('Activity type updated successfully');
      } else {
        // Create new
        await createActivityType(payload);
        toast.success('Activity type created successfully');
      }

      await loadActivityTypes();
      setShowAddDialog(false);
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err: any) {
      const errorMsg = err.response?.data?.error || 'Failed to save activity type';
      setError(errorMsg);
      toast.error(errorMsg);
    }
  };

  const handleDelete = async (activityType: ActivityType) => {
    if (!confirm(`Delete "${activityType.title}"? This will deactivate the activity type.`)) {
      return;
    }

    try {
      setError(null);
      await deleteActivityType(activityType.activityTypeId);
      toast.success('Activity type deleted successfully');
      await loadActivityTypes();
    } catch (err: any) {
      const errorMsg = err.response?.data?.error || 'Failed to delete activity type';
      setError(errorMsg);
      toast.error(errorMsg);
    }
  };

  // Filter active and inactive activity types
  const activeActivityTypes = activityTypes.filter(at => at.isActive !== false && at.isActive !== undefined);
  const inactiveActivityTypes = activityTypes.filter(at => at.isActive === false);

  return (
    <div className="space-y-6">
      {/* Success Message */}
      {successMessage && (
        <div className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-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-green-500 rounded-md">
            <CheckCircle className="w-4 h-4 text-white shrink-0" />
          </div>
          <p className="text-sm font-medium text-green-900">{successMessage}</p>
        </div>
      )}

      {/* 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 sm:flex-row items-start sm:items-center justify-between gap-3 sm: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">
                <FileText className="w-5 h-5 text-white" />
              </div>
              <div>
                <CardTitle className="text-lg sm:text-xl font-semibold text-slate-900">Activity Types</CardTitle>
                <CardDescription className="text-sm">
                  Manage dealer claim activity types
                </CardDescription>
              </div>
            </div>
            <Button
              onClick={handleAdd}
              className="gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm"
            >
              <Plus className="w-4 h-4" />
              <span className="hidden xs:inline">Add Activity Type</span>
              <span className="xs:hidden">Add</span>
            </Button>
          </div>
        </CardHeader>
      </Card>

      {/* Activity Types List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
        </div>
      ) : activeActivityTypes.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">
              <FileText className="w-10 h-10 text-slate-400" />
            </div>
            <p className="text-slate-700 font-medium text-lg">No activity types found</p>
            <p className="text-sm text-slate-500 mt-2 mb-6">Add activity types for dealer claim management</p>
            <Button
              onClick={handleAdd}
              variant="outline"
              className="gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm"
            >
              <Plus className="w-4 h-4" />
              Add First Activity Type
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4 sm:space-y-6">
          {/* Active Activity Types */}
          <Card className="shadow-lg border-0 rounded-md">
            <CardHeader className="pb-3 sm:pb-4 border-b border-slate-100">
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-base sm:text-lg font-semibold text-slate-900">Active Activity Types</CardTitle>
                  <CardDescription className="text-xs sm:text-sm">
                    {activeActivityTypes.length} active type{activeActivityTypes.length !== 1 ? 's' : ''}
                  </CardDescription>
                </div>
                <div className="p-2 bg-green-50 rounded-md">
                  <CheckCircle className="w-4 h-4 text-green-600" />
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-3 pt-4">
              {activeActivityTypes.map(activityType => (
                <div
                  key={activityType.activityTypeId}
                  className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-2 flex-wrap">
                      <p className="font-semibold text-slate-900 text-sm sm:text-base">{activityType.title}</p>
                      <Badge variant="outline" className="bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 border-green-300 text-[10px] sm:text-xs font-medium shadow-sm">
                        Active
                      </Badge>
                    </div>
                    <div className="flex flex-wrap gap-3 text-xs sm:text-sm text-slate-600">
                      {activityType.itemCode && (
                        <span className="font-medium">Item Code: <span className="text-slate-900">{activityType.itemCode}</span></span>
                      )}
                      {activityType.taxationType && (
                        <span className="font-medium">Taxation: <span className="text-slate-900">{activityType.taxationType}</span></span>
                      )}
                      {activityType.sapRefNo && (
                        <span className="font-medium">SAP Ref: <span className="text-slate-900">{activityType.sapRefNo}</span></span>
                      )}
                      {activityType.creditPostingOn && (
                        <span className="font-medium">Credit Posting On: <Badge variant="secondary" className="ml-1 bg-slate-200 text-slate-800">{activityType.creditPostingOn}</Badge></span>
                      )}
                      {!activityType.itemCode && !activityType.taxationType && !activityType.sapRefNo && !activityType.creditPostingOn && (
                        <span className="text-slate-500 italic">No additional details</span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2 sm:gap-2 self-end sm:self-auto">
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => handleEdit(activityType)}
                      className="gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm"
                    >
                      <Edit2 className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                      <span className="hidden xs:inline">Edit</span>
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => handleDelete(activityType)}
                      className="gap-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 text-xs sm:text-sm"
                    >
                      <Trash2 className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                      <span className="hidden xs:inline">Delete</span>
                    </Button>
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>

          {/* Inactive Activity Types */}
          {inactiveActivityTypes.length > 0 && (
            <Card className="shadow-lg border-0 rounded-md border-amber-200">
              <CardHeader className="pb-3 sm:pb-4 border-b border-slate-100">
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="text-base sm:text-lg font-semibold text-slate-900">Inactive Activity Types</CardTitle>
                    <CardDescription className="text-xs sm:text-sm">
                      {inactiveActivityTypes.length} inactive type{inactiveActivityTypes.length !== 1 ? 's' : ''}
                    </CardDescription>
                  </div>
                  <div className="p-2 bg-amber-50 rounded-md">
                    <AlertCircle className="w-4 h-4 text-amber-600" />
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-3 pt-4">
                {inactiveActivityTypes.map(activityType => (
                  <div
                    key={activityType.activityTypeId}
                    className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-amber-50/50 border border-amber-200 rounded-md hover:bg-amber-50 hover:border-amber-300 transition-all shadow-sm"
                  >
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2 flex-wrap">
                        <p className="font-semibold text-slate-700 text-sm sm:text-base line-through">{activityType.title}</p>
                        <Badge variant="outline" className="bg-gradient-to-r from-amber-50 to-orange-50 text-amber-800 border-amber-300 text-[10px] sm:text-xs font-medium shadow-sm">
                          Inactive
                        </Badge>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 sm:gap-2 self-end sm:self-auto">
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => handleEdit(activityType)}
                        className="gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm"
                      >
                        <Edit2 className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                        <span className="hidden xs:inline">Edit</span>
                      </Button>
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>
          )}
        </div>
      )}

      {/* Add/Edit Dialog */}
      <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
        <DialogContent className="sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0">
          <DialogHeader className="pb-4 border-b border-slate-100 px-6 pt-6 flex-shrink-0">
            <div className="flex items-center gap-3">
              <div className="p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg shadow-md">
                <FileText className="w-5 h-5 text-white" />
              </div>
              <div className="flex-1">
                <DialogTitle className="text-xl font-semibold text-slate-900">
                  {editingActivityType ? 'Edit Activity Type' : 'Add New Activity Type'}
                </DialogTitle>
                <DialogDescription className="text-sm text-slate-600 mt-1">
                  {editingActivityType ? 'Update activity type information' : 'Add a new activity type for dealer claim management'}
                </DialogDescription>
              </div>
            </div>
          </DialogHeader>

          <div className="space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0">
            {/* Title Field */}
            <div className="space-y-2">
              <Label htmlFor="title" className="text-sm font-semibold text-slate-900 flex items-center gap-1">
                Title <span className="text-red-500">*</span>
              </Label>
              <Input
                id="title"
                placeholder="e.g., Riders Mania Claims, Legal Claims Reimbursement"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"
              />
              <p className="text-xs text-slate-500">Enter the activity type title</p>
            </div>

            {/* Item Code Field */}
            <div className="space-y-2">
              <Label htmlFor="itemCode" className="text-sm font-semibold text-slate-900">
                Item Code <span className="text-slate-400 font-normal text-xs">(Optional)</span>
              </Label>
              <Input
                id="itemCode"
                placeholder="e.g., 1, 2, 3"
                value={formData.itemCode}
                onChange={(e) => setFormData({ ...formData, itemCode: e.target.value })}
                className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"
              />
              <p className="text-xs text-slate-500">Optional item code for the activity type</p>
            </div>

            {/* Taxation Type Field */}
            <div className="space-y-2">
              <Label htmlFor="taxationType" className="text-sm font-semibold text-slate-900 flex items-center gap-1">
                Taxation Type <span className="text-red-500">*</span>
              </Label>
              <Select
                value={formData.taxationType}
                onValueChange={(value) => setFormData({ ...formData, taxationType: value })}
              >
                <SelectTrigger id="taxationType" className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm">
                  <SelectValue placeholder="Select Taxation Type" />
                </SelectTrigger>
                <SelectContent className="rounded-lg">
                  <SelectItem value="GST" className="p-3">GST</SelectItem>
                  <SelectItem value="Non GST" className="p-3">Non GST</SelectItem>
                </SelectContent>
              </Select>
              <p className="text-xs text-slate-500">Select whether the activity is GST or Non-GST</p>
            </div>

            {/* SAP Reference Number Field */}
            <div className="space-y-2">
              <Label htmlFor="sapRefNo" className="text-sm font-semibold text-slate-900 flex items-center gap-1">
                Claim Document Type (SAP Ref) <span className="text-red-500">*</span>
              </Label>
              <Input
                id="sapRefNo"
                placeholder="e.g., ZCNS, ZRE"
                value={formData.sapRefNo}
                onChange={(e) => setFormData({ ...formData, sapRefNo: e.target.value })}
                className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"
              />
              <p className="text-xs text-slate-500">Required SAP reference number for CSV generation</p>
            </div>

            {/* Credit Posting On Field */}
            <div className="space-y-2">
              <Label htmlFor="creditPostingOn" className="text-sm font-semibold text-slate-900 flex items-center gap-1">
                Credit Posting On <span className="text-red-500">*</span>
              </Label>
              <Select
                value={formData.creditPostingOn}
                onValueChange={(value) => setFormData({ ...formData, creditPostingOn: value })}
              >
                <SelectTrigger id="creditPostingOn" className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm">
                  <SelectValue placeholder="Select Credit Posting Group" />
                </SelectTrigger>
                <SelectContent className="rounded-lg">
                  <SelectItem value="Vehicles" className="p-3">Vehicles</SelectItem>
                  <SelectItem value="Spares" className="p-3">Spares</SelectItem>
                  <SelectItem value="GMA" className="p-3">GMA</SelectItem>
                  <SelectItem value="Apparel" className="p-3">Apparel</SelectItem>
                </SelectContent>
              </Select>
              <p className="text-xs text-slate-500">Categorize for dealer validation (Vehicle, Spares, GMA, or Apparel)</p>
            </div>
          </div>

          <DialogFooter className="gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0">
            <Button
              variant="outline"
              onClick={() => setShowAddDialog(false)}
              className="h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm"
            >
              Cancel
            </Button>
            <Button
              onClick={handleSave}
              disabled={!formData.title.trim() || !formData.taxationType || !formData.sapRefNo.trim() || !formData.creditPostingOn}
              className="h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <FileText className="w-4 h-4 mr-2" />
              {editingActivityType ? 'Update Activity Type' : 'Add Activity Type'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

