import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { createClient } from "@supabase/supabase-js";
import { Lock, FileText, FolderOpen, Download, File, Shield } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { format } from "date-fns";

// Use anon client for public access
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;
const anonClient = createClient(supabaseUrl, supabaseAnonKey);

export default function SharedAccessPage() {
  const { token } = useParams<{ token: string }>();
  const [step, setStep] = useState<"code" | "content">("code");
  const [code, setCode] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);
  const [linkData, setLinkData] = useState<any>(null);
  const [documents, setDocuments] = useState<any[]>([]);

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

  const validateToken = async () => {
    setLoading(true);
    const { data, error } = await anonClient
      .from("shared_links")
      .select("*")
      .eq("share_token", token || "")
      .eq("is_public", true)
      .single();

    if (error || !data) {
      setError("This share link is invalid or has expired.");
      setLoading(false);
      return;
    }
    setLinkData(data);
    setLoading(false);
  };

  const handleSubmitCode = async () => {
    if (!linkData) return;
    if (code.toUpperCase().trim() !== linkData.access_code) {
      setError("Invalid access code. Please try again.");
      return;
    }
    setError("");
    setLoading(true);

    // Fetch documents based on share type
    if (linkData.share_type === "folder") {
      const folderCategory = linkData.folder_name === "Uncategorized" ? "general" : linkData.folder_name;
      const { data } = await anonClient
        .from("documents")
        .select("id, title, file_name, file_url, file_size, created_at, category")
        .eq("category", folderCategory)
        .order("created_at", { ascending: false });
      setDocuments(data || []);
    } else {
      const { data } = await anonClient
        .from("documents")
        .select("id, title, file_name, file_url, file_size, created_at, category")
        .eq("id", linkData.document_id)
        .single();
      setDocuments(data ? [data] : []);
    }
    setStep("content");
    setLoading(false);
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  if (error && step === "code" && !linkData) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background p-4">
        <Card className="max-w-md w-full">
          <CardContent className="pt-8 text-center space-y-4">
            <Lock className="h-12 w-12 mx-auto text-destructive" />
            <h2 className="text-xl font-bold">Link Not Found</h2>
            <p className="text-muted-foreground text-sm">{error}</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (step === "code") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background p-4">
        <Card className="max-w-md w-full">
          <CardHeader className="text-center">
            <div className="mx-auto mb-3 h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center">
              <Shield className="h-7 w-7 text-primary" />
            </div>
            <CardTitle className="text-xl">
              {linkData?.share_type === "folder" ? "Shared Folder" : "Shared Document"}
            </CardTitle>
            <p className="text-sm text-muted-foreground mt-1">
              {linkData?.share_type === "folder"
                ? `Access files in "${linkData?.folder_name}"`
                : "Access shared document"}
            </p>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="text-sm font-medium mb-2 block">Enter Access Code</label>
              <Input
                value={code}
                onChange={(e) => { setCode(e.target.value.toUpperCase()); setError(""); }}
                placeholder="Enter code..."
                className="text-center text-lg font-mono tracking-[0.2em] font-bold"
                maxLength={8}
                onKeyDown={(e) => e.key === "Enter" && handleSubmitCode()}
              />
              {error && <p className="text-xs text-destructive mt-2">{error}</p>}
            </div>
            <Button className="w-full gap-2" onClick={handleSubmitCode} disabled={!code}>
              <Lock className="h-4 w-4" /> Access Files
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="border-b bg-card">
        <div className="max-w-5xl mx-auto px-6 py-4 flex items-center gap-3">
          <FolderOpen className="h-5 w-5 text-primary" />
          <div>
            <h1 className="font-bold">
              {linkData?.share_type === "folder" ? linkData?.folder_name : "Shared Document"}
            </h1>
            <p className="text-xs text-muted-foreground">{documents.length} file(s) available</p>
          </div>
        </div>
      </div>
      <div className="max-w-5xl mx-auto px-6 py-6">
        <div className="rounded-lg border bg-card overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="text-xs font-bold uppercase">Name</TableHead>
                <TableHead className="text-xs font-bold uppercase w-[140px]">Date Added</TableHead>
                <TableHead className="text-xs font-bold uppercase w-[100px] text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {documents.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={3} className="text-center py-12 text-muted-foreground">
                    No files available in this share.
                  </TableCell>
                </TableRow>
              ) : documents.map((d) => (
                <TableRow key={d.id}>
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <File className="h-5 w-5 text-primary shrink-0" />
                      <div>
                        <p className="font-medium text-sm">{d.title}</p>
                        {d.file_name && <p className="text-xs text-muted-foreground">{d.file_name}</p>}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">{format(new Date(d.created_at), "MMM d, yyyy")}</div>
                  </TableCell>
                  <TableCell className="text-right">
                    {d.file_url && (
                      <Button variant="ghost" size="icon" className="h-8 w-8" asChild>
                        <a href={d.file_url} target="_blank" rel="noopener noreferrer">
                          <Download className="h-4 w-4" />
                        </a>
                      </Button>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
}
