
'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { MapPin, DollarSign, Calendar, TrendingUp } from 'lucide-react';
import { toast } from 'sonner';

export default function MarketplacePage() {
  const { data: session } = useSession();
  const router = useRouter();
  const [contracts, setContracts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    region: '',
    serviceType: '',
    maxPrice: '',
    minPrice: '',
  });

  useEffect(() => {
    if (session?.user.role !== 'CONTRACTOR') {
      router.push('/dashboard');
      return;
    }
    fetchContracts();
  }, [session]);

  const fetchContracts = async () => {
    try {
      const params = new URLSearchParams();
      if (filters.region) params.append('region', filters.region);
      if (filters.serviceType) params.append('serviceType', filters.serviceType);
      if (filters.maxPrice) params.append('maxPrice', filters.maxPrice);
      if (filters.minPrice) params.append('minPrice', filters.minPrice);

      const res = await fetch(`/api/marketplace/contracts?${params.toString()}`);
      const data = await res.json();
      setContracts(data);
    } catch (error) {
      console.error('Error fetching contracts:', error);
      toast.error('Failed to load contracts');
    } finally {
      setLoading(false);
    }
  };

  const handlePurchase = async (contractId: string, listPrice: number) => {
    try {
      const res = await fetch('/api/marketplace/purchase', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contractId, offeredPrice: listPrice }),
      });

      if (res.ok) {
        toast.success('Contract purchased successfully!');
        fetchContracts();
        router.push('/dashboard');
      } else {
        const error = await res.json();
        toast.error(error.error || 'Failed to purchase contract');
      }
    } catch (error) {
      console.error('Error purchasing contract:', error);
      toast.error('Failed to purchase contract');
    }
  };

  if (loading) {
    return <div className="p-8">Loading contracts...</div>;
  }

  return (
    <div className="container mx-auto p-6">
      <div className="mb-8">
        <h1 className="text-3xl font-bold mb-2">Contract Marketplace</h1>
        <p className="text-muted-foreground">
          Browse and purchase signed contracts from customers ready for work
        </p>
      </div>

      {/* Filters */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Filters</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-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>

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

            <Input
              placeholder="Max Price"
              type="number"
              value={filters.maxPrice}
              onChange={(e) =>
                setFilters((prev) => ({ ...prev, maxPrice: e.target.value }))
              }
            />

            <Button onClick={fetchContracts}>Apply Filters</Button>
          </div>
        </CardContent>
      </Card>

      {/* Contract Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {contracts.map((contract) => (
          <Card key={contract.id} className="hover:shadow-lg transition-shadow">
            <CardHeader>
              <div className="flex items-start justify-between">
                <div>
                  <CardTitle className="text-lg">
                    {contract.quote.lead.services.join(', ')}
                  </CardTitle>
                  <CardDescription>
                    Contract #{contract.contractNumber}
                  </CardDescription>
                </div>
                <Badge variant="success">Available</Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center text-sm">
                <MapPin className="w-4 h-4 mr-2 text-muted-foreground" />
                <span>
                  {contract.quote.lead.city}, {contract.quote.lead.state}
                </span>
                {contract.distance && (
                  <Badge variant="outline" className="ml-2">
                    {contract.distance.toFixed(1)} km away
                  </Badge>
                )}
              </div>

              <div className="flex items-center text-sm">
                <DollarSign className="w-4 h-4 mr-2 text-muted-foreground" />
                <span className="font-semibold">
                  ${contract.quote.total.toLocaleString()}
                </span>
                <span className="text-muted-foreground ml-1">project value</span>
              </div>

              <div className="flex items-center text-sm">
                <TrendingUp className="w-4 h-4 mr-2 text-muted-foreground" />
                <span className="font-semibold">
                  ${contract.listPrice?.toLocaleString() || (contract.quote.total * 0.15).toLocaleString()}
                </span>
                <span className="text-muted-foreground ml-1">purchase price</span>
              </div>

              <div className="flex items-center text-sm">
                <Calendar className="w-4 h-4 mr-2 text-muted-foreground" />
                <span className="text-muted-foreground">
                  Created {new Date(contract.createdAt).toLocaleDateString()}
                </span>
              </div>
            </CardContent>
            <CardFooter>
              <Button
                className="w-full"
                onClick={() =>
                  handlePurchase(
                    contract.id,
                    contract.listPrice || contract.quote.total * 0.15
                  )
                }
              >
                Purchase Contract
              </Button>
            </CardFooter>
          </Card>
        ))}
      </div>

      {contracts.length === 0 && (
        <div className="text-center py-12">
          <p className="text-muted-foreground">
            No contracts available matching your filters
          </p>
        </div>
      )}
    </div>
  );
}
