
'use client';

import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { FileText, Clock, CheckCircle, XCircle, Eye, DollarSign, MapPin, Calendar } from 'lucide-react';
import { toast } from 'sonner';
import { QuoteDetailsDialog } from '@/components/customer/quote-details-dialog';

type Quote = {
  id: string;
  quoteNumber: string;
  services: string[];
  total: number;
  status: string;
  isAccepted: boolean;
  validUntil: string;
  createdAt: string;
  sentAt: string | null;
  propertyData: {
    address?: string;
    coordinates?: { lat: number; lng: number };
    measurements?: any;
  };
  lineItems: Array<{
    description: string;
    quantity: number;
    unit: string;
    unitPrice: number;
    total: number;
  }>;
  subtotal: number;
  discounts: number;
  taxes: number;
  notes?: string;
  termsConditions?: string;
  lead?: {
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    address: string;
  };
};

export function CustomerDashboardClient() {
  const { data: session, status } = useSession() || {};
  const [quotes, setQuotes] = useState<Quote[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedQuote, setSelectedQuote] = useState<Quote | null>(null);

  useEffect(() => {
    if (status === 'authenticated') {
      fetchQuotes();
    }
  }, [status]);

  const fetchQuotes = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/customer/quotes');
      
      if (!response.ok) {
        throw new Error('Failed to fetch quotes');
      }

      const data = await response.json();
      setQuotes(data.quotes || []);
    } catch (error) {
      console.error('Error fetching quotes:', error);
      toast.error('Failed to load quotes');
    } finally {
      setLoading(false);
    }
  };

  const handleAcceptQuote = async (quoteId: string) => {
    try {
      const response = await fetch(`/api/customer/quotes/${quoteId}/accept`, {
        method: 'POST',
      });

      if (!response.ok) {
        throw new Error('Failed to accept quote');
      }

      toast.success('Quote accepted successfully!');
      fetchQuotes();
    } catch (error) {
      console.error('Error accepting quote:', error);
      toast.error('Failed to accept quote');
    }
  };

  const handleRejectQuote = async (quoteId: string, reason: string) => {
    try {
      const response = await fetch(`/api/customer/quotes/${quoteId}/reject`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ reason }),
      });

      if (!response.ok) {
        throw new Error('Failed to reject quote');
      }

      toast.success('Quote rejected');
      fetchQuotes();
    } catch (error) {
      console.error('Error rejecting quote:', error);
      toast.error('Failed to reject quote');
    }
  };

  const getStatusBadge = (quote: Quote) => {
    if (quote.status === 'ACCEPTED' || quote.isAccepted) {
      return <Badge className="bg-green-600 hover:bg-green-700">Accepted</Badge>;
    }
    if (quote.status === 'REJECTED') {
      return <Badge variant="destructive">Rejected</Badge>;
    }
    if (quote.status === 'EXPIRED') {
      return <Badge variant="secondary">Expired</Badge>;
    }
    if (quote.status === 'SENT' || quote.status === 'VIEWED') {
      return <Badge className="bg-blue-600 hover:bg-blue-700">Pending Review</Badge>;
    }
    return <Badge variant="outline">{quote.status}</Badge>;
  };

  const isQuoteExpired = (validUntil: string) => {
    return new Date(validUntil) < new Date();
  };

  const filterQuotes = (filterType: string) => {
    switch (filterType) {
      case 'pending':
        return quotes.filter(q => 
          (q.status === 'SENT' || q.status === 'VIEWED') && 
          !q.isAccepted && 
          !isQuoteExpired(q.validUntil)
        );
      case 'accepted':
        return quotes.filter(q => q.status === 'ACCEPTED' || q.isAccepted);
      case 'expired':
        return quotes.filter(q => isQuoteExpired(q.validUntil) && q.status !== 'ACCEPTED' && q.status !== 'REJECTED');
      default:
        return quotes;
    }
  };

  const stats = {
    total: quotes.length,
    pending: filterQuotes('pending').length,
    accepted: filterQuotes('accepted').length,
    expired: filterQuotes('expired').length,
  };

  if (loading) {
    return (
      <div className="container mx-auto py-10">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
            <p className="mt-4 text-muted-foreground">Loading your quotes...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-6 space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold tracking-tight">My Dashboard</h1>
        <p className="text-muted-foreground mt-2">
          Welcome back, {session?.user?.name || 'Customer'}! View and manage your quotes below.
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Quotes</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground">All time quotes</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Pending Review</CardTitle>
            <Clock className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.pending}</div>
            <p className="text-xs text-muted-foreground">Awaiting your decision</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Accepted</CardTitle>
            <CheckCircle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.accepted}</div>
            <p className="text-xs text-muted-foreground">Approved quotes</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Expired</CardTitle>
            <XCircle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.expired}</div>
            <p className="text-xs text-muted-foreground">Past valid date</p>
          </CardContent>
        </Card>
      </div>

      {/* Quotes Tabs */}
      <Tabs defaultValue="all" className="space-y-4">
        <TabsList>
          <TabsTrigger value="all">All Quotes ({stats.total})</TabsTrigger>
          <TabsTrigger value="pending">Pending ({stats.pending})</TabsTrigger>
          <TabsTrigger value="accepted">Accepted ({stats.accepted})</TabsTrigger>
          <TabsTrigger value="expired">Expired ({stats.expired})</TabsTrigger>
        </TabsList>

        <TabsContent value="all" className="space-y-4">
          <QuotesList 
            quotes={filterQuotes('all')} 
            onViewQuote={setSelectedQuote}
            onAcceptQuote={handleAcceptQuote}
            onRejectQuote={handleRejectQuote}
            getStatusBadge={getStatusBadge}
          />
        </TabsContent>

        <TabsContent value="pending" className="space-y-4">
          <QuotesList 
            quotes={filterQuotes('pending')} 
            onViewQuote={setSelectedQuote}
            onAcceptQuote={handleAcceptQuote}
            onRejectQuote={handleRejectQuote}
            getStatusBadge={getStatusBadge}
          />
        </TabsContent>

        <TabsContent value="accepted" className="space-y-4">
          <QuotesList 
            quotes={filterQuotes('accepted')} 
            onViewQuote={setSelectedQuote}
            onAcceptQuote={handleAcceptQuote}
            onRejectQuote={handleRejectQuote}
            getStatusBadge={getStatusBadge}
          />
        </TabsContent>

        <TabsContent value="expired" className="space-y-4">
          <QuotesList 
            quotes={filterQuotes('expired')} 
            onViewQuote={setSelectedQuote}
            onAcceptQuote={handleAcceptQuote}
            onRejectQuote={handleRejectQuote}
            getStatusBadge={getStatusBadge}
          />
        </TabsContent>
      </Tabs>

      {/* Quote Details Dialog */}
      {selectedQuote && (
        <QuoteDetailsDialog
          quote={selectedQuote}
          open={!!selectedQuote}
          onClose={() => setSelectedQuote(null)}
          onAccept={handleAcceptQuote}
          onReject={handleRejectQuote}
        />
      )}
    </div>
  );
}

type QuotesListProps = {
  quotes: Quote[];
  onViewQuote: (quote: Quote) => void;
  onAcceptQuote: (quoteId: string) => void;
  onRejectQuote: (quoteId: string, reason: string) => void;
  getStatusBadge: (quote: Quote) => React.ReactNode;
};

function QuotesList({ quotes, onViewQuote, onAcceptQuote, onRejectQuote, getStatusBadge }: QuotesListProps) {
  if (quotes.length === 0) {
    return (
      <Card>
        <CardContent className="flex flex-col items-center justify-center py-12">
          <FileText className="h-12 w-12 text-muted-foreground mb-4" />
          <h3 className="text-lg font-semibold mb-2">No quotes found</h3>
          <p className="text-sm text-muted-foreground">You don't have any quotes in this category yet.</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="grid gap-4 md:grid-cols-1 lg:grid-cols-2">
      {quotes.map((quote) => (
        <Card key={quote.id} className="hover:shadow-lg transition-shadow">
          <CardHeader>
            <div className="flex items-start justify-between">
              <div className="space-y-1">
                <CardTitle className="text-lg">{quote.quoteNumber}</CardTitle>
                <CardDescription>
                  {quote.services.join(', ')}
                </CardDescription>
              </div>
              {getStatusBadge(quote)}
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <div className="flex items-center text-sm text-muted-foreground">
                <MapPin className="h-4 w-4 mr-2" />
                <span className="truncate">{quote.propertyData?.address || 'No address'}</span>
              </div>
              <div className="flex items-center text-sm text-muted-foreground">
                <Calendar className="h-4 w-4 mr-2" />
                <span>Valid until: {new Date(quote.validUntil).toLocaleDateString()}</span>
              </div>
              <div className="flex items-center text-sm font-semibold">
                <DollarSign className="h-4 w-4 mr-2" />
                <span>Total: ${quote.total.toLocaleString()}</span>
              </div>
            </div>

            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                className="flex-1"
                onClick={() => onViewQuote(quote)}
              >
                <Eye className="h-4 w-4 mr-2" />
                View Details
              </Button>
              
              {(quote.status === 'SENT' || quote.status === 'VIEWED') && 
               !quote.isAccepted && 
               new Date(quote.validUntil) > new Date() && (
                <Button
                  size="sm"
                  className="flex-1"
                  onClick={() => onAcceptQuote(quote.id)}
                >
                  <CheckCircle className="h-4 w-4 mr-2" />
                  Accept
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
