import React, { useState, useEffect } from 'react';
import { useAuth } from '../../context/AuthContext';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Input } from '../../components/ui/input';
import StatusBadge from '@/components/StatusBadge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../../components/ui/select';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../../components/ui/dropdown-menu';
import { Badge } from '../../components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '../../components/ui/table';
import api from '../../utils/api';
import { toast } from 'sonner';
import {
  DollarSign,
  Heart,
  Users,
  Globe,
  Search,
  Loader2,
  Download,
  FileDown,
  Calendar,
  ChevronDown,
  ChevronUp,
  ExternalLink,
  Copy,
  CreditCard,
  Info
} from 'lucide-react';

const AdminDonations = () => {
  const { hasPermission } = useAuth();
  const [donations, setDonations] = useState([]);
  const [filteredDonations, setFilteredDonations] = useState([]);
  const [stats, setStats] = useState({});
  const [loading, setLoading] = useState(true);
  const [exporting, setExporting] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [expandedRows, setExpandedRows] = useState(new Set());

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

  useEffect(() => {
    filterDonations();
  }, [searchQuery, typeFilter, statusFilter, startDate, endDate, donations]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [donationsResponse, statsResponse] = await Promise.all([
        api.get('/admin/donations'),
        api.get('/admin/donations/stats')
      ]);

      setDonations(donationsResponse.data);
      setStats(statsResponse.data);
    } catch (error) {
      console.error('Failed to fetch donation data:', error);
      toast.error('Failed to load donation data');
    } finally {
      setLoading(false);
    }
  };

  const filterDonations = () => {
    let filtered = [...donations];

    // Search filter (donor name or email)
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(donation =>
        donation.donor_name?.toLowerCase().includes(query) ||
        donation.donor_email?.toLowerCase().includes(query)
      );
    }

    // Type filter
    if (typeFilter !== 'all') {
      filtered = filtered.filter(donation => donation.donation_type === typeFilter);
    }

    // Status filter
    if (statusFilter !== 'all') {
      filtered = filtered.filter(donation => donation.status === statusFilter);
    }

    // Date range filter
    if (startDate) {
      filtered = filtered.filter(donation =>
        new Date(donation.created_at) >= new Date(startDate)
      );
    }

    if (endDate) {
      filtered = filtered.filter(donation =>
        new Date(donation.created_at) <= new Date(endDate)
      );
    }

    setFilteredDonations(filtered);
  };

  const handleExport = async (exportType) => {
    setExporting(true);
    try {
      const params = exportType === 'current' ? {
        donation_type: typeFilter !== 'all' ? typeFilter : undefined,
        status: statusFilter !== 'all' ? statusFilter : undefined,
        start_date: startDate || undefined,
        end_date: endDate || undefined,
        search: searchQuery || undefined
      } : {};

      const response = await api.get('/admin/donations/export', {
        params,
        responseType: 'blob'
      });

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `donations_export_${new Date().toISOString().split('T')[0]}.csv`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);

      toast.success('Donations exported successfully');
    } catch (error) {
      console.error('Failed to export donations:', error);
      toast.error('Failed to export donations');
    } finally {
      setExporting(false);
    }
  };

  const formatPrice = (cents) => {
    return `$${(cents / 100).toFixed(2)}`;
  };

  const formatDate = (dateString) => {
    if (!dateString) return 'N/A';
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const toggleRowExpansion = (donationId) => {
    setExpandedRows((prev) => {
      const newExpanded = new Set(prev);
      if (newExpanded.has(donationId)) {
        newExpanded.delete(donationId);
      } else {
        newExpanded.add(donationId);
      }
      return newExpanded;
    });
  };

  const copyToClipboard = async (text, label) => {
    try {
      await navigator.clipboard.writeText(text);
      toast.success(`${label} copied to clipboard`);
    } catch (error) {
      toast.error('Failed to copy to clipboard');
    }
  };
  /*
  */

  const getTypeBadgeColor = (type) => {
    return type === 'member' ? 'bg-[var(--green-light)]' : 'bg-brand-purple ';
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-12 w-12 animate-spin text-brand-purple " />
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
          Donation Management
        </h1>
        <p className="text-brand-purple  mt-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
          Track and manage all donations from members and the public
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid md:grid-cols-4 gap-6">
        <Card className="p-6 bg-background rounded-2xl border-2 border-[var(--neutral-800)]">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Total Donations
              </p>
              <p className="text-3xl font-bold text-[var(--purple-ink)] mt-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                {stats.total_donations || 0}
              </p>
            </div>
            <div className="p-3 bg-[var(--neutral-800)]/20 rounded-full">
              <Heart className="h-6 w-6 text-brand-purple " />
            </div>
          </div>
        </Card>

        <Card className="p-6 bg-background rounded-2xl border-2 border-[var(--neutral-800)]">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Member Donations
              </p>
              <p className="text-3xl font-bold text-[var(--green-light)] mt-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                {stats.member_donations || 0}
              </p>
            </div>
            <div className="p-3 bg-[var(--green-light)]/10 rounded-full">
              <Users className="h-6 w-6 text-[var(--green-light)]" />
            </div>
          </div>
        </Card>

        <Card className="p-6 bg-background rounded-2xl border-2 border-[var(--neutral-800)]">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Public Donations
              </p>
              <p className="text-3xl font-bold text-brand-purple  mt-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                {stats.public_donations || 0}
              </p>
            </div>
            <div className="p-3 bg-[var(--neutral-800)]/20 rounded-full">
              <Globe className="h-6 w-6 text-brand-purple " />
            </div>
          </div>
        </Card>

        <Card className="p-6 bg-background rounded-2xl border-2 border-[var(--neutral-800)]">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Total Amount
              </p>
              <p className="text-3xl font-bold text-[var(--purple-ink)] mt-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                {stats.total_amount || '$0.00'}
              </p>
            </div>
            <div className="p-3 bg-[var(--neutral-800)]/20 rounded-full">
              <DollarSign className="h-6 w-6 text-brand-purple " />
            </div>
          </div>
        </Card>
      </div>

      {/* Filters and Actions */}
      <Card className="p-6 bg-background rounded-2xl border-2 border-[var(--neutral-800)]">
        <div className="space-y-4">
          {/* Search and Export Row */}
          <div className="flex flex-col md:flex-row gap-4 justify-between">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-brand-purple " />
              <Input
                placeholder="Search by donor name or email..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
              />
            </div>
            {hasPermission('donations.export') && (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    disabled={exporting}
                    className="bg-[var(--green-light)] text-white hover:bg-[var(--green-soft)] rounded-full px-6 py-3 flex items-center gap-2"
                  >
                    <Download className="h-4 w-4" />
                    {exporting ? 'Exporting...' : 'Export'}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-56 bg-background rounded-xl border-2 border-[var(--neutral-800)] shadow-lg">
                  <DropdownMenuItem
                    onClick={() => handleExport('all')}
                    className="cursor-pointer hover:bg-[var(--lavender-300)] rounded-lg p-3"
                  >
                    <FileDown className="h-4 w-4 mr-2 text-brand-purple " />
                    <span className="text-[var(--purple-ink)]">Export All Donations</span>
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => handleExport('current')}
                    className="cursor-pointer hover:bg-[var(--lavender-300)] rounded-lg p-3"
                  >
                    <FileDown className="h-4 w-4 mr-2 text-brand-purple " />
                    <span className="text-[var(--purple-ink)]">Export Current View</span>
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            )}
          </div>

          {/* Filters Row */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
              <Select value={typeFilter} onValueChange={setTypeFilter}>
                <SelectTrigger className="rounded-xl border-2 border-[var(--neutral-800)]">
                  <SelectValue placeholder="All Types" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Types</SelectItem>
                  <SelectItem value="member">Member Donations</SelectItem>
                  <SelectItem value="public">Public Donations</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="rounded-xl border-2 border-[var(--neutral-800)]">
                  <SelectValue placeholder="All Statuses" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Statuses</SelectItem>
                  <SelectItem value="completed">Completed</SelectItem>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="failed">Failed</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="rounded-xl border-2 border-[var(--neutral-800)]"
                placeholder="Start Date"
              />
            </div>

            <div>
              <Input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="rounded-xl border-2 border-[var(--neutral-800)]"
                placeholder="End Date"
              />
            </div>
          </div>

          {/* Active Filters Summary */}
          {(searchQuery || typeFilter !== 'all' || statusFilter !== 'all' || startDate || endDate) && (
            <div className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Showing {filteredDonations.length} of {donations.length} donations
            </div>
          )}
        </div>
      </Card>

      {/* Donations Table */}
      <Card className="bg-background rounded-2xl border-2 border-[var(--neutral-800)] overflow-hidden">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Donor</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Amount</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Date</TableHead>
                <TableHead>Payment Method</TableHead>
                <TableHead className="text-center">Details</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredDonations.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="p-12 text-center">
                    <div className="flex flex-col items-center gap-3">
                      <Heart className="h-12 w-12 text-[var(--neutral-800)]" />
                      <p className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                        {donations.length === 0 ? 'No donations yet' : 'No donations match your filters'}
                      </p>
                    </div>
                  </TableCell>
                </TableRow>
              ) : (
                filteredDonations.map((donation) => {
                  const isExpanded = expandedRows.has(donation.id);
                  return (
                    <React.Fragment key={donation.id}>
                      <TableRow>
                        <TableCell>
                          <div>
                            <p className="font-medium text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                              {donation.donor_name || 'Anonymous'}
                            </p>
                            <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                              {donation.donor_email || 'No email'}
                            </p>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge
                            className={`${getTypeBadgeColor(donation.donation_type)} text-white border-none  px-3 py-1`}
                            style={{ fontFamily: "'Inter', sans-serif" }}
                          >
                            {donation.donation_type === 'member' ? 'Member' : 'Public'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <p className="font-semibold text-[var(--purple-ink)] text-lg" style={{ fontFamily: "'Inter', sans-serif" }}>
                            {donation.amount}
                          </p>
                        </TableCell>
                        <TableCell>
                          <StatusBadge status={donation.status} />
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2 text-brand-purple ">
                            <Calendar className="h-4 w-4" />
                            <span style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                              {formatDate(donation.created_at)}
                            </span>
                          </div>
                        </TableCell>
                        <TableCell>
                          <p className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif capitalize" }}>
                            {donation.payment_method || 'N/A'}
                          </p>
                        </TableCell>
                        <TableCell className="text-center">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => toggleRowExpansion(donation.id)}
                            className="text-brand-purple hover:bg-[var(--neutral-800)]"
                          >
                            {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                          </Button>
                        </TableCell>
                      </TableRow>
                      {isExpanded && (
                        <TableRow className="bg-[var(--lavender-400)]/30">
                          <TableCell colSpan={7} className="p-6">
                            <div className="space-y-4">
                              <h4 className="font-semibold text-[var(--purple-ink)] text-lg mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
                                Transaction Details
                              </h4>
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                {/* Payment Information */}
                                <div className="space-y-3">
                                  <h5 className="font-medium text-[var(--purple-ink)] flex items-center gap-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                                    <CreditCard className="h-4 w-4" />
                                    Payment Information
                                  </h5>
                                  <div className="space-y-2 text-sm">
                                    {donation.payment_completed_at && (
                                      <div className="flex justify-between">
                                        <span className="text-brand-purple ">Payment Date:</span>
                                        <span className="text-[var(--purple-ink)] font-medium">{formatDate(donation.payment_completed_at)}</span>
                                      </div>
                                    )}
                                    {donation.payment_method && (
                                      <div className="flex justify-between">
                                        <span className="text-brand-purple ">Payment Method:</span>
                                        <span className="text-[var(--purple-ink)] font-medium capitalize">{donation.payment_method}</span>
                                      </div>
                                    )}
                                    {donation.card_brand && donation.card_last4 && (
                                      <div className="flex justify-between">
                                        <span className="text-brand-purple ">Card:</span>
                                        <span className="text-[var(--purple-ink)] font-medium">{donation.card_brand} ****{donation.card_last4}</span>
                                      </div>
                                    )}
                                  </div>
                                </div>

                                {/* Stripe Transaction IDs */}
                                <div className="space-y-3">
                                  <h5 className="font-medium text-[var(--purple-ink)] flex items-center gap-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                                    <Info className="h-4 w-4" />
                                    Stripe Transaction IDs
                                  </h5>
                                  <div className="space-y-2 text-sm">
                                    {donation.stripe_payment_intent_id && (
                                      <div className="flex items-center justify-between gap-2">
                                        <span className="text-brand-purple ">Payment Intent:</span>
                                        <div className="flex items-center gap-1">
                                          <code className="text-xs bg-[var(--neutral-800)]/30 px-2 py-1 rounded text-[var(--purple-ink)]">
                                            {donation.stripe_payment_intent_id.substring(0, 20)}...
                                          </code>
                                          <Button
                                            size="sm"
                                            variant="ghost"
                                            onClick={() => copyToClipboard(donation.stripe_payment_intent_id, 'Payment Intent ID')}
                                          >
                                            <Copy className="h-3 w-3" />
                                          </Button>
                                        </div>
                                      </div>
                                    )}
                                    {donation.stripe_charge_id && (
                                      <div className="flex items-center justify-between gap-2">
                                        <span className="text-brand-purple ">Charge ID:</span>
                                        <div className="flex items-center gap-1">
                                          <code className="text-xs bg-[var(--neutral-800)]/30 px-2 py-1 rounded text-[var(--purple-ink)]">
                                            {donation.stripe_charge_id.substring(0, 20)}...
                                          </code>
                                          <Button
                                            size="sm"
                                            variant="ghost"
                                            onClick={() => copyToClipboard(donation.stripe_charge_id, 'Charge ID')}
                                          >
                                            <Copy className="h-3 w-3" />
                                          </Button>
                                        </div>
                                      </div>
                                    )}
                                    {donation.stripe_customer_id && (
                                      <div className="flex items-center justify-between gap-2">
                                        <span className="text-brand-purple ">Customer ID:</span>
                                        <div className="flex items-center gap-1">
                                          <code className="text-xs bg-[var(--neutral-800)]/30 px-2 py-1 rounded text-[var(--purple-ink)]">
                                            {donation.stripe_customer_id.substring(0, 20)}...
                                          </code>
                                          <Button
                                            size="sm"
                                            variant="ghost"
                                            onClick={() => copyToClipboard(donation.stripe_customer_id, 'Customer ID')}
                                          >
                                            <Copy className="h-3 w-3" />
                                          </Button>
                                        </div>
                                      </div>
                                    )}
                                    {donation.stripe_receipt_url && (
                                      <div className="flex items-center justify-between gap-2">
                                        <span className="text-brand-purple ">Receipt:</span>
                                        <Button
                                          size="sm"
                                          variant="outline"
                                          onClick={() => window.open(donation.stripe_receipt_url, '_blank')}
                                          className="text-brand-purple hover:bg-[var(--neutral-800)]"
                                        >
                                          <ExternalLink className="h-3 w-3 mr-1" />
                                          View Receipt
                                        </Button>
                                      </div>
                                    )}
                                  </div>
                                </div>
                              </div>
                            </div>
                          </TableCell>
                        </TableRow>
                      )}
                    </React.Fragment>
                  );
                })
              )}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* This Month Summary */}
      {stats.this_month_count > 0 && (
        <Card className="p-6 bg-gradient-to-r from-[var(--lavender-400)] to-[var(--lavender-300)] rounded-2xl border-2 border-[var(--neutral-800)]">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-brand-purple  font-medium" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                This Month's Donations
              </p>
              <p className="text-2xl font-bold text-[var(--purple-ink)] mt-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                {stats.this_month_count} donations • {stats.this_month_amount}
              </p>
            </div>
            <div className="p-4 bg-background rounded-full shadow-sm">
              <Heart className="h-8 w-8 text-[var(--orange-light)]" />
            </div>
          </div>
        </Card>
      )}
    </div>
  );
};

export default AdminDonations;
