
'use client';

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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { toast } from 'sonner';

export function AdminFilterDashboard() {
  const [filters, setFilters] = useState({
    region: '',
    serviceType: '',
    paymentStatus: '',
    quoteStatus: '',
    contractStatus: '',
    minRating: '',
    dateFrom: '',
    dateTo: '',
  });

  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const fetchFilteredData = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      Object.entries(filters).forEach(([key, value]) => {
        if (value) params.append(key, value);
      });

      const res = await fetch(`/api/admin/filters?${params.toString()}`);
      if (res.ok) {
        const result = await res.json();
        setData(result);
      } else {
        toast.error('Failed to fetch filtered data');
      }
    } catch (error) {
      console.error('Error fetching filtered data:', error);
      toast.error('Failed to fetch filtered data');
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="space-y-6">
      {/* Filters Card */}
      <Card>
        <CardHeader>
          <CardTitle>Advanced Filters</CardTitle>
          <CardDescription>
            Filter quotes, contracts, and contractors by multiple criteria
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
            <Select
              value={filters.region}
              onValueChange={(value) => setFilters((prev) => ({ ...prev, region: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="Region" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Regions</SelectItem>
                <SelectItem value="SOUTH_AFRICA">South Africa</SelectItem>
                <SelectItem value="UNITED_KINGDOM">United Kingdom</SelectItem>
                <SelectItem value="AUSTRALIA">Australia</SelectItem>
                <SelectItem value="USA">USA</SelectItem>
              </SelectContent>
            </Select>

            <Select
              value={filters.serviceType}
              onValueChange={(value) => setFilters((prev) => ({ ...prev, serviceType: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="Service Type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Services</SelectItem>
                <SelectItem value="roofing">Roofing</SelectItem>
                <SelectItem value="gutters">Gutters</SelectItem>
                <SelectItem value="solar">Solar</SelectItem>
                <SelectItem value="painting">Painting</SelectItem>
              </SelectContent>
            </Select>

            <Select
              value={filters.paymentStatus}
              onValueChange={(value) => setFilters((prev) => ({ ...prev, paymentStatus: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="Payment Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Payments</SelectItem>
                <SelectItem value="UNPAID">Unpaid</SelectItem>
                <SelectItem value="DEPOSIT_PAID">Deposit Paid</SelectItem>
                <SelectItem value="PAID">Paid</SelectItem>
                <SelectItem value="OVERDUE">Overdue</SelectItem>
              </SelectContent>
            </Select>

            <Input
              type="number"
              placeholder="Min Rating"
              value={filters.minRating}
              onChange={(e) => setFilters((prev) => ({ ...prev, minRating: e.target.value }))}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
            <Select
              value={filters.quoteStatus}
              onValueChange={(value) => setFilters((prev) => ({ ...prev, quoteStatus: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="Quote Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Quotes</SelectItem>
                <SelectItem value="DRAFT">Draft</SelectItem>
                <SelectItem value="SENT">Sent</SelectItem>
                <SelectItem value="ACCEPTED">Accepted</SelectItem>
                <SelectItem value="REJECTED">Rejected</SelectItem>
              </SelectContent>
            </Select>

            <Select
              value={filters.contractStatus}
              onValueChange={(value) => setFilters((prev) => ({ ...prev, contractStatus: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="Contract Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Contracts</SelectItem>
                <SelectItem value="DRAFT">Draft</SelectItem>
                <SelectItem value="ACTIVE">Active</SelectItem>
                <SelectItem value="IN_PROGRESS">In Progress</SelectItem>
                <SelectItem value="COMPLETED">Completed</SelectItem>
              </SelectContent>
            </Select>

            <Input
              type="date"
              placeholder="From Date"
              value={filters.dateFrom}
              onChange={(e) => setFilters((prev) => ({ ...prev, dateFrom: e.target.value }))}
            />

            <Input
              type="date"
              placeholder="To Date"
              value={filters.dateTo}
              onChange={(e) => setFilters((prev) => ({ ...prev, dateTo: e.target.value }))}
            />
          </div>

          <div className="flex gap-2">
            <Button onClick={fetchFilteredData} disabled={loading}>
              {loading ? 'Loading...' : 'Apply Filters'}
            </Button>
            <Button
              variant="outline"
              onClick={() => {
                setFilters({
                  region: '',
                  serviceType: '',
                  paymentStatus: '',
                  quoteStatus: '',
                  contractStatus: '',
                  minRating: '',
                  dateFrom: '',
                  dateTo: '',
                });
                fetchFilteredData();
              }}
            >
              Clear Filters
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Statistics Cards */}
      {data?.stats && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card>
            <CardHeader>
              <CardTitle>{data.stats.totalQuotes}</CardTitle>
              <CardDescription>Total Quotes</CardDescription>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>{data.stats.totalContracts}</CardTitle>
              <CardDescription>Total Contracts</CardDescription>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>{data.stats.totalContractors}</CardTitle>
              <CardDescription>Active Contractors</CardDescription>
            </CardHeader>
          </Card>
        </div>
      )}

      {/* Results Tabs */}
      {data && (
        <Tabs defaultValue="quotes">
          <TabsList>
            <TabsTrigger value="quotes">Quotes ({data.quotes.length})</TabsTrigger>
            <TabsTrigger value="contracts">Contracts ({data.contracts.length})</TabsTrigger>
            <TabsTrigger value="contractors">Contractors ({data.contractors.length})</TabsTrigger>
          </TabsList>

          <TabsContent value="quotes" className="space-y-4">
            {data.quotes.map((quote: any) => (
              <Card key={quote.id}>
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div>
                      <CardTitle className="text-lg">#{quote.quoteNumber}</CardTitle>
                      <CardDescription>
                        {quote.lead.firstName} {quote.lead.lastName} • {quote.lead.city}
                      </CardDescription>
                    </div>
                    <div className="flex gap-2">
                      <Badge>{quote.status}</Badge>
                      <Badge variant="outline">{quote.paymentStatus}</Badge>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-sm">
                    Total: ${quote.total.toLocaleString()} • Created:{' '}
                    {new Date(quote.createdAt).toLocaleDateString()}
                  </p>
                </CardContent>
              </Card>
            ))}
          </TabsContent>

          <TabsContent value="contracts" className="space-y-4">
            {data.contracts.map((contract: any) => (
              <Card key={contract.id}>
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div>
                      <CardTitle className="text-lg">#{contract.contractNumber}</CardTitle>
                      <CardDescription>
                        {contract.quote.lead.firstName} {contract.quote.lead.lastName}
                      </CardDescription>
                    </div>
                    <Badge>{contract.status}</Badge>
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-sm">
                    Value: ${contract.quote.total.toLocaleString()} •{' '}
                    {contract.partner?.user.name || 'Unassigned'}
                  </p>
                </CardContent>
              </Card>
            ))}
          </TabsContent>

          <TabsContent value="contractors" className="space-y-4">
            {data.contractors.map((contractor: any) => (
              <Card key={contractor.id}>
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div>
                      <CardTitle className="text-lg">{contractor.user.name}</CardTitle>
                      <CardDescription>{contractor.companyName}</CardDescription>
                    </div>
                    {contractor.performanceMetrics[0] && (
                      <Badge>
                        ⭐ {contractor.performanceMetrics[0].averageRating.toFixed(1)}
                      </Badge>
                    )}
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-sm">
                    License: {contractor.licenseNumber} • {contractor.serviceAreas.join(', ')}
                  </p>
                </CardContent>
              </Card>
            ))}
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
}
