
'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { MilestoneTracker } from '@/components/milestones/milestone-tracker';
import { VehicleTrackingMap } from '@/components/tracking/vehicle-tracking-map';
import { MapPin, Calendar, DollarSign } from 'lucide-react';
import { toast } from 'sonner';

export default function CustomerPortalPage() {
  const params = useParams();
  const token = (params?.token as string) || '';
  const [portalData, setPortalData] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (token) {
      fetchPortalData();
    }
  }, [token]);

  const fetchPortalData = async () => {
    try {
      const res = await fetch(`/api/customer-portal/${token}`);
      if (res.ok) {
        const data = await res.json();
        setPortalData(data);
      } else {
        toast.error('Invalid or expired access token');
      }
    } catch (error) {
      console.error('Error fetching portal data:', error);
      toast.error('Failed to load portal data');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p>Loading your project...</p>
        </div>
      </div>
    );
  }

  if (!portalData) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle>Access Denied</CardTitle>
            <CardDescription>
              Your access token is invalid or has expired.
            </CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  const { contract, milestones, photos, tracking, permissions } = portalData;
  const contractData = contract || {};
  const quoteData = contractData.quote || {};
  const leadData = quoteData.lead || {};

  return (
    <div className="min-h-screen bg-background">
      <div className="bg-primary text-primary-foreground py-6 px-4">
        <div className="container mx-auto">
          <h1 className="text-2xl font-bold mb-2">Your Project Portal</h1>
          <p className="text-sm opacity-90">
            Track your project in real-time with Quote2Contract
          </p>
        </div>
      </div>

      <div className="container mx-auto p-4 md:p-6 max-w-7xl">
        <Card className="mb-6">
          <CardHeader>
            <div className="flex items-start justify-between">
              <div>
                <CardTitle>Contract #{contractData.contractNumber || 'N/A'}</CardTitle>
                <CardDescription>
                  {leadData.services?.join(', ') || 'Services'}
                </CardDescription>
              </div>
              <Badge>{contractData.status || 'UNKNOWN'}</Badge>
            </div>
          </CardHeader>
          <CardContent className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="flex items-center gap-3">
              <MapPin className="w-5 h-5 text-muted-foreground" />
              <div>
                <p className="text-sm font-medium">Location</p>
                <p className="text-sm text-muted-foreground">
                  {leadData.city || 'N/A'}, {leadData.state || 'N/A'}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <DollarSign className="w-5 h-5 text-muted-foreground" />
              <div>
                <p className="text-sm font-medium">Project Value</p>
                <p className="text-sm text-muted-foreground">
                  ${(quoteData.total || 0).toLocaleString()}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <Calendar className="w-5 h-5 text-muted-foreground" />
              <div>
                <p className="text-sm font-medium">Start Date</p>
                <p className="text-sm text-muted-foreground">
                  {contractData.startDate
                    ? new Date(contractData.startDate).toLocaleDateString()
                    : 'Not scheduled'}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Tabs defaultValue="progress" className="space-y-4">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="progress">Progress</TabsTrigger>
            <TabsTrigger value="tracking" disabled={!permissions?.canViewTracking}>
              Live Tracking
            </TabsTrigger>
            <TabsTrigger value="photos" disabled={!permissions?.canViewPhotos}>
              Photos
            </TabsTrigger>
            <TabsTrigger value="documents">Documents</TabsTrigger>
          </TabsList>

          <TabsContent value="progress">
            {permissions?.canViewMilestones ? (
              <MilestoneTracker contractId={contractData.id} canEdit={false} />
            ) : (
              <Card>
                <CardContent className="p-6">
                  <p className="text-muted-foreground">
                    Milestone tracking is not available
                  </p>
                </CardContent>
              </Card>
            )}
          </TabsContent>

          <TabsContent value="tracking">
            {permissions?.canViewTracking && tracking && tracking.length > 0 ? (
              <VehicleTrackingMap
                contractId={contractData.id}
                siteLocation={{
                  lat: leadData.latitude || 0,
                  lng: leadData.longitude || 0,
                }}
                initialTracking={tracking}
              />
            ) : (
              <Card>
                <CardContent className="p-6">
                  <p className="text-muted-foreground">
                    No tracking data available yet
                  </p>
                </CardContent>
              </Card>
            )}
          </TabsContent>

          <TabsContent value="photos">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {photos && photos.length > 0 ? (
                photos.map((photo: any) => (
                  <Card key={photo.id}>
                    <CardContent className="p-3">
                      <p className="text-sm">{photo.fileName}</p>
                    </CardContent>
                  </Card>
                ))
              ) : (
                <Card className="col-span-full">
                  <CardContent className="p-6">
                    <p className="text-muted-foreground text-center">
                      No photos uploaded yet
                    </p>
                  </CardContent>
                </Card>
              )}
            </div>
          </TabsContent>

          <TabsContent value="documents">
            <Card>
              <CardHeader>
                <CardTitle>Project Documents</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  Signed contract and project documents
                </p>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
